package com.zhiche.lisa.lspm.service.carrier.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.zhiche.lisa.core.enums.*;
import com.zhiche.lisa.core.enums.exception.CarrierEnum;
import com.zhiche.lisa.core.enums.exception.VehicleException;
import com.zhiche.lisa.core.supports.BaseException;
import com.zhiche.lisa.core.utils.Account.AccountUtil;
import com.zhiche.lisa.core.utils.Account.JwtAccountVO;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import com.zhiche.lisa.core.utils.RegexUtil;
import com.zhiche.lisa.core.utils.redislog.RedisLogUtil;
import com.zhiche.lisa.lspm.config.LspmProperties;
import com.zhiche.lisa.lspm.dao.mapper.carrier.CarrierInfoMapper;
import com.zhiche.lisa.lspm.dao.model.carrier.*;
import com.zhiche.lisa.lspm.dao.model.carrier.bo.*;
import com.zhiche.lisa.lspm.dao.model.driver.*;
import com.zhiche.lisa.lspm.dao.model.fleet.Fleet;
import com.zhiche.lisa.lspm.dao.model.fleet.FleetBind;
import com.zhiche.lisa.lspm.dao.model.lsp.LspInfo;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerInfo;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerLicense;
import com.zhiche.lisa.lspm.dao.model.trailer.TrailerLicenseAttach;
import com.zhiche.lisa.lspm.dao.model.trailer.bo.*;
import com.zhiche.lisa.lspm.dto.CarrierToErpDTO;
import com.zhiche.lisa.lspm.dto.VehicleDTO;
import com.zhiche.lisa.lspm.service.carrier.*;
import com.zhiche.lisa.lspm.service.driver.*;
import com.zhiche.lisa.lspm.service.fleet.IFleetBindService;
import com.zhiche.lisa.lspm.service.fleet.IFleetService;
import com.zhiche.lisa.lspm.service.fleet.impl.FleetBindServiceImpl;
import com.zhiche.lisa.lspm.service.lsp.LspInfoService;
import com.zhiche.lisa.lspm.service.trailer.TrailerInfoService;
import com.zhiche.lisa.lspm.service.trailer.TrailerLicenseAttachService;
import com.zhiche.lisa.lspm.service.trailer.TrailerLicenseService;
import com.zhiche.lisa.lspm.service.upload.UploadService;
import com.zhiche.lisa.lspm.service.utils.DictionaryUtil;
import com.zhiche.lisa.lspm.service.utils.IntegrationUtil;
import com.zhiche.lisa.lspm.service.utils.MdmUtil;
import com.zhiche.lisa.lspm.service.utils.UaaUtil;
import com.zhiche.lisa.lspm.vo.common.AccountVO;
import com.zhiche.lisa.lspm.vo.common.LicenseTypeVo;
import com.zhiche.lisa.lspm.vo.common.TransportationTypeVO;
import com.zhiche.lisa.lspm.vo.driver.AttachVO;
import com.zhiche.lisa.lspm.vo.fleet.FleetBindVO;
import com.zhiche.lisa.lspm.vo.fleet.FleetCarId;
import com.zhiche.lisa.lspm.vo.vehicle.*;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 牵引车 service
 *
 * @author lbl
 * @since 2018-05-23
 */
@Service
public class CarrierInfoServiceImpl extends ServiceImpl<CarrierInfoMapper, CarrierInfo> implements ICarrierInfoService {

    private static final Logger LOGGER = LoggerFactory.getLogger(CarrierInfoServiceImpl.class);

    @Autowired
    private ICarrierLicenseService carrierLicenseService;
    @Autowired
    private ICarrierLicenseAttachService carrierLicenseAttachService;
    @Autowired
    private ICarrierCardService carrierCardService;
    @Autowired
    private LspInfoService lspInfoService;
    @Autowired
    private ICarrierAuditLogService iCarrierAuditLogService;
    @Autowired
    private TrailerInfoService trailerInfoService;
    @Autowired
    private ICarrierTrailerBindService carrierTrailerBindService;
    @Autowired
    private IDriverCarrierBindService driverCarrierBindService;
    @Autowired
    private IDriverService driverService;
    @Autowired
    private ICarrierTrailerBindLogService carrierTrailerBindLogService;
    @Autowired
    private TrailerLicenseService trailerLicenseService;
    @Autowired
    private TrailerLicenseAttachService trailerLicenseAttachService;
    @Autowired
    private IDriverCarrierBindLogService driverCarrierBindLogService;
    @Autowired
    private UploadService uploadService;
    @Autowired
    private IDriverLicenseService driverLicenseService;
    @Autowired
    private MdmUtil mdmUtil;
    @Autowired
    private IFleetBindService fleetBindService;
    @Autowired
    private ICarrierCardService cardService;
    @Autowired
    private UaaUtil uaaUtil;
    @Autowired
    private IFleetService fleetService;
    @Autowired
    private ICarrierInfoService carrierInfoService;
    @Autowired
    private IntegrationUtil integrationUtil;
    @Autowired
    private LspmProperties properties;
    @Autowired
    private FleetBindServiceImpl fleetBindServiceImpl;
    @Autowired
    private IDriverCheckinService driverCheckinService;

    @Value("${integration.url}")
    private String integrationUrl;
    @Value("${integration.carrierPushErpUrl}")
    private String carrierPushErpUrl;
    @Value("${integration.driverPushErpUrl}")
    private String driverPushErpUrl;
    @Value("${uaa.socketTimeout}")
    private Integer socketTimeout;
    @Value("${integration.trailerPushErpUrl}")
    private String trailerPushErpUrl;
    @Value("${lisa.tms.driverWaybillUrl}")
    private String driverWaybillUrl;
    @Value("${uaa.updateTenantOfAccountUrl}")
    private String updateTenantOfAccountUrl;
    @Value("${uaa.url}")
    private String uaaUrl;
    @Value("${integrationToOtm}")
    private String integrationToOtm;
    @Value("${logRedis.isTest}")
    private boolean isTest;

    @Override
    public Page<CarrierInfoLineVO> carrierInfoLine(Page<CarrierInfoLineBO> page, String authorization) {
        if (page == null) return null;
        EntityWrapper<CarrierInfoLineBO> ew = whereCarrierLine(page);
        Page<CarrierInfoLineVO> pageVo = new Page<>();
        List<CarrierInfoLineVO> list = baseMapper.carrierInfoLine(page, ew);
        list.forEach(carrierInfoLineVO -> {
            if (!Strings.isNullOrEmpty(carrierInfoLineVO.getCreator())) {
                AccountVO accountVO = uaaUtil.getAccountById(carrierInfoLineVO.getCreator(), authorization);
                if (Objects.nonNull(accountVO)) {
                    carrierInfoLineVO.setCreator(accountVO.getIdentifier());
                }
            }
        });
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(list);
        return pageVo;
    }

    @Override
    public Page<CarrierInfoLineVO> authedCarrierInfoLine(Page<CarrierInfoLineBO> page) {
        if (page == null) return null;
        EntityWrapper<CarrierInfoLineBO> ew = whereCarrierLine(page);
        Page<CarrierInfoLineVO> pageVo = new Page<>();
        List<CarrierInfoLineVO> list = baseMapper.authedCarrierInfoLine(page, ew);
        BeanUtils.copyProperties(page, pageVo);
        pageVo.setRecords(list);
        return pageVo;
    }


    private EntityWrapper<CarrierInfoLineBO> whereCarrierLine(Page<CarrierInfoLineBO> page) {
        EntityWrapper<CarrierInfoLineBO> ew = new EntityWrapper<>();
        // 车牌号
        if (page.getCondition() != null
                && !StringUtils.isEmpty(page.getCondition().get("plate"))) {
            ew.like("plate", page.getCondition().get("plate").toString().trim());
        }
        if (page.getCondition() != null
                && Objects.nonNull(page.getCondition().get("tenantId"))) {
            ew.eq("tenant_id", page.getCondition().get("tenantId").toString().trim());
        }
        // 承运商 id
        if (page.getCondition() != null
                && !StringUtils.isEmpty(page.getCondition().get("lspId"))) {
            ew.eq("lsp_id", page.getCondition().get("lspId").toString().trim());
        }
        if (page.getCondition() != null
                && !StringUtils.isEmpty(page.getCondition().get("canDel"))) {
            ew.eq("is_delete", page.getCondition().get("canDel").toString().trim());
        } else {
            ew.eq("is_delete", 0);
        }
        ew.orderBy("gmt_create", false);
        return ew;
    }

    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void addCarrierInfo(ModifyCarrierInfoBO modifyCarrierInfoBO) throws BaseException {

        try {
            // 校验数据
            CarrierInfo carrierInfo = new CarrierInfo();

            if (Objects.isNull(modifyCarrierInfoBO.getTenantId())) throw new BaseException("请选择所属公司");
            checkModifyData(modifyCarrierInfoBO, "insert");
            if (!Strings.isNullOrEmpty(modifyCarrierInfoBO.getOwnerName()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyCarrierInfoBO.getOwnerName()))
                    throw new BaseException("车主姓名不合法");
            if (!Strings.isNullOrEmpty(modifyCarrierInfoBO.getManufacturer()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyCarrierInfoBO.getManufacturer()))
                    throw new BaseException("生产厂商不合法");
            if (!Strings.isNullOrEmpty(modifyCarrierInfoBO.getModel()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyCarrierInfoBO.getModel()))
                    throw new BaseException("生产厂商不合法");
            if (Objects.isNull(modifyCarrierInfoBO.getTenantId())) throw new BaseException("请选择所属公司");


//            Wrapper<CarrierInfo> carrierInfoWrapper = new EntityWrapper<>();
//            carrierInfoWrapper.eq("driver_id", modifyCarrierInfoBO.getDriverId());
//            List<CarrierInfo> carrierInfoList = selectList(carrierInfoWrapper);
//            if (!CollectionUtils.isEmpty(carrierInfoList))
//                throw new BaseException("司机已被绑定");

            Long lspId = lspInfoService.getLspIdByTenantId(modifyCarrierInfoBO.getTenantId());
            if (!Objects.isNull(lspId)) modifyCarrierInfoBO.setLspId(lspId);
            // 添加牵引车基础信息

            BeanUtils.copyProperties(modifyCarrierInfoBO, carrierInfo);
            carrierInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
            carrierInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
            carrierInfo.setCreateFrom(SourceEnum.LSPM.getText());
            this.insert(carrierInfo);
            List<ModifyCarrierLicenseBO> modifyCarrierLicenseBOList = modifyCarrierInfoBO.getModifyCarrierLicenseBOList();
            for (ModifyCarrierLicenseBO modifyCarrierLicenseBO : modifyCarrierLicenseBOList) {
                CarrierLicense carrierLicense = new CarrierLicense();
                BeanUtils.copyProperties(modifyCarrierLicenseBO, carrierLicense);
                carrierLicense.setCarrierId(carrierInfo.getId());
                carrierLicenseService.insert(carrierLicense);
            }


            // 添加牵引车卡片信息
            List<CarrierCard> carrierCardList = new ArrayList<>();
            List<ModifyCarrierCardBO> modifyCarrierCarBOList = modifyCarrierInfoBO.getModifyCarrierCardBOList();
            for (ModifyCarrierCardBO modifyCarrierCarBO : modifyCarrierCarBOList) {
                CarrierCard carrierCard = new CarrierCard();
                BeanUtils.copyProperties(modifyCarrierCarBO, carrierCard);
                carrierCard.setCarrierId(carrierInfo.getId());
                carrierCardList.add(carrierCard);
            }
            if (!CollectionUtils.isEmpty(carrierCardList)) {
                carrierCardService.insertBatch(carrierCardList);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception ex) {
            throw new BaseException(-1, "操作异常请重试");
        }

    }

    private CarrierLicense getLicenseByIdOrType(ModifyCarrierLicenseBO carrierLicense, Long carrierId) {
        CarrierLicense license = new CarrierLicense();
        if (Objects.isNull(carrierLicense.getId())) {
            EntityWrapper<CarrierLicense> ew = new EntityWrapper<>();
            ew.eq("carrier_id", carrierId);
            ew.eq("license_type_id", carrierLicense.getLicenseTypeId());
            List<CarrierLicense> carrierLicenses = carrierLicenseService.selectList(ew);
            if (!CollectionUtils.isEmpty(carrierLicenses)) {
                license = carrierLicenses.get(0);
            }
        } else {
            EntityWrapper<CarrierLicense> ew = new EntityWrapper<>();
            ew.eq("id", carrierLicense.getId());
            List<CarrierLicense> carrierLicenses = carrierLicenseService.selectList(ew);
            if (!CollectionUtils.isEmpty(carrierLicenses)) {
                license = carrierLicenses.get(0);
            }
        }
        return license;
    }

    @Override
    public void updateLicense(ModifyCarrierInfoBO modifyCarrierInfoBO) {
        if (Objects.isNull(modifyCarrierInfoBO.getId())) throw new BaseException("未绑定承运商");
        List<ModifyCarrierLicenseBO> toCarrierLicenseList = modifyCarrierInfoBO.getModifyCarrierLicenseBOList();
        toCarrierLicenseList.forEach(modifyCarrierLicenseBO -> {
            CarrierLicense license = new CarrierLicense();
            BeanUtils.copyProperties(modifyCarrierLicenseBO, license);
            license.setId(getLicenseByIdOrType(modifyCarrierLicenseBO, modifyCarrierInfoBO.getId()).getId());
            if (Objects.isNull(license.getId())) {
                license.setCarrierId(modifyCarrierInfoBO.getId());
                carrierLicenseService.insert(license);
                // 添加承运商证照附件
                List<CarrierLicenseAttach> carrierLicenseAttaches = modifyCarrierLicenseBO.getCarrierLicenseAttachList();
                for (CarrierLicenseAttach driverLicenseAttache :
                        carrierLicenseAttaches) {
                    driverLicenseAttache.setCarrierId(modifyCarrierInfoBO.getId());
                    driverLicenseAttache.setLicenseId(license.getId());
                }
                if (!CollectionUtils.isEmpty(carrierLicenseAttaches))
                    carrierLicenseAttachService.insertBatch(carrierLicenseAttaches);
            } else {
                for (CarrierLicenseAttach carrierLicenseAttach :
                        modifyCarrierLicenseBO.getCarrierLicenseAttachList()) {
                    //删除原有附件
                    EntityWrapper<CarrierLicenseAttach> ewAttach = new EntityWrapper<>();
                    ewAttach.eq("carrier_id", modifyCarrierInfoBO.getId());
                    ewAttach.eq("license_id", license.getId());
                    ewAttach.eq("attach_type", carrierLicenseAttach.getAttachType());
                    //获取对应牵引车现有证照的附件信息
                    CarrierLicenseAttach licenseAttach = carrierLicenseAttachService.selectOne(ewAttach);
                    //若存在附件
                    if (Objects.nonNull(licenseAttach)) {
                        //和本次上传的附件不一样，软删之后在新增，不一样直接跳过本次新增
                        if (!carrierLicenseAttach.getAttachKey().equals(licenseAttach.getAttachKey())) {
                            carrierLicenseAttachService.updateOldAttachDeleteState(licenseAttach);
                        } else {
                            continue;
                        }
                    }
                    //修改附件对应信息，写入库
                    carrierLicenseAttach.setCarrierId(modifyCarrierInfoBO.getId());
                    carrierLicenseAttach.setLicenseId(license.getId());
                    carrierLicenseAttachService.insert(carrierLicenseAttach);
                }
            }
        });
    }

    @Override
    public void deleteLicense(ModifyCarrierLicenseBO modifyCarrierLicenseBO) {
        for (CarrierLicenseAttach carrierLicenseAttach :
                modifyCarrierLicenseBO.getCarrierLicenseAttachList()) {
            if (Objects.isNull(carrierLicenseAttach.getId())) {
                EntityWrapper<CarrierLicense> ew = new EntityWrapper<>();
                ew.eq("license_type_id", modifyCarrierLicenseBO.getLicenseTypeId());
                ew.eq("carrier_id", modifyCarrierLicenseBO.getCarrierId());
                List<CarrierLicense> carrierLicenses = carrierLicenseService.selectList(ew);
                if (CollectionUtils.isEmpty(carrierLicenses)) throw new BaseException("未查找到匹配删除项");
                EntityWrapper<CarrierLicenseAttach> ewAttach = new EntityWrapper<>();
                CarrierLicense carrierLicense = carrierLicenses.get(0);
                ewAttach.eq("carrier_id", modifyCarrierLicenseBO.getCarrierId());
                ewAttach.eq("license_id", carrierLicense.getId());
                ewAttach.eq("attach_type", carrierLicenseAttach.getAttachType());
//                ewAttach.eq("is_delete", "0");
//                carrierLicenseAttachService.updateDeleteState(ewAttach);
                CarrierLicenseAttach licenseAttach = carrierLicenseAttachService.selectOne(ewAttach);
                carrierLicenseAttachService.updateOldAttachDeleteState(licenseAttach);
            } else {
                EntityWrapper<CarrierLicenseAttach> ewAttach = new EntityWrapper<>();
                ewAttach.eq("id", carrierLicenseAttach.getId());
//                ewAttach.eq("is_delete", "0");
//                carrierLicenseAttachService.updateDeleteState(ewAttach);
                CarrierLicenseAttach licenseAttach = carrierLicenseAttachService.selectOne(ewAttach);
                carrierLicenseAttachService.updateOldAttachDeleteState(licenseAttach);
            }
        }

    }

    @Override
    public ModifyCarrierInfoBO findModifyInfo(Long id) {
        if (id == null)
            throw new BaseException(-1, "牵引车ID不存在");

        Boolean isHaveAttach = false;

        // 查询编辑承运商信息
        CarrierInfo carrierInfo = this.selectById(id);
        if (carrierInfo == null)
            throw new BaseException(-1, "牵引车信息不存在");

        ModifyCarrierInfoBO modifyCarrierInfoBO = new ModifyCarrierInfoBO();

        BeanUtils.copyProperties(carrierInfo, modifyCarrierInfoBO);

        // 查询所属承运商
        if (modifyCarrierInfoBO.getLspId() != null) {
            LspInfo lspInfo = lspInfoService.selectById(modifyCarrierInfoBO.getLspId());
            if (lspInfo != null) {
                modifyCarrierInfoBO.setLspName(lspInfo.getName());
            }
        }

        // 查找牵引车的证照信息
        Wrapper<CarrierLicense> licenseEntity = new EntityWrapper<>();
        licenseEntity.eq("carrier_id", id);
        List<CarrierLicense> licenseList = carrierLicenseService.selectList(licenseEntity);
        if (!CollectionUtils.isEmpty(licenseList)) {
            List<ModifyCarrierLicenseBO> modifyCarrierLicenseBOList = new ArrayList<>();
            for (CarrierLicense license : licenseList) {
                ModifyCarrierLicenseBO modifyCarrierLicenseBO = new ModifyCarrierLicenseBO();
                BeanUtils.copyProperties(license, modifyCarrierLicenseBO);

                // 查找证照的附件信息
                Wrapper<CarrierLicenseAttach> licenseAttachEntity = new EntityWrapper<>();
                licenseAttachEntity.eq("license_id", license.getId());
                List<CarrierLicenseAttach> carrierLicenseAttachList = carrierLicenseAttachService.selectList(licenseAttachEntity);
                if (!CollectionUtils.isEmpty(carrierLicenseAttachList)) {
                    modifyCarrierLicenseBO.setCarrierLicenseAttachList(carrierLicenseAttachList);
                    isHaveAttach = true;
                }

                // 判断证照有效性
                modifyCarrierLicenseBO.setStatus(getValidStatus(license, isHaveAttach));

                modifyCarrierLicenseBOList.add(modifyCarrierLicenseBO);
            }
            if (!CollectionUtils.isEmpty(modifyCarrierLicenseBOList)) {
                modifyCarrierInfoBO.setModifyCarrierLicenseBOList(modifyCarrierLicenseBOList);
            }
        }

        // 获取牵引车下的卡信息
        Wrapper<CarrierCard> carrierEntity = new EntityWrapper<>();
        carrierEntity.eq("carrier_id", carrierInfo.getId());
        List<CarrierCard> carrierCardList = carrierCardService.selectList(carrierEntity);
        List<ModifyCarrierCardBO> modifyCarrierCardBOList = new ArrayList<>();
        for (CarrierCard carrierCard : carrierCardList) {
            ModifyCarrierCardBO modifyCarrierCardBO = new ModifyCarrierCardBO();
            BeanUtils.copyProperties(carrierCard, modifyCarrierCardBO);

            String cardType = mdmUtil.getCardType(modifyCarrierCardBO.getIssuerTypeCode());
            modifyCarrierCardBO.setIssuerTypeName(cardType);

            modifyCarrierCardBOList.add(modifyCarrierCardBO);
        }
        if (!CollectionUtils.isEmpty(modifyCarrierCardBOList)) {
            modifyCarrierInfoBO.setModifyCarrierCardBOList(modifyCarrierCardBOList);
        }
        return modifyCarrierInfoBO;
    }

    /**
     * 新增证照  删除证照
     * 新增证照附件  删除证照附件
     */
    @Transactional(propagation = Propagation.REQUIRED)
    @Override
    public void modifyCarrierInfo(ModifyCarrierInfoBO modifyCarrierInfoBO) throws BaseException {

        try {
            // 校验数据
            if (Objects.isNull(modifyCarrierInfoBO.getTenantId())) throw new BaseException("请选择所属公司");
            checkModifyData(modifyCarrierInfoBO, "modify");
            if (!Strings.isNullOrEmpty(modifyCarrierInfoBO.getOwnerName()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyCarrierInfoBO.getOwnerName()))
                    throw new BaseException("车主姓名不合法");
            if (!Strings.isNullOrEmpty(modifyCarrierInfoBO.getManufacturer()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyCarrierInfoBO.getManufacturer()))
                    throw new BaseException("生产厂商不合法");
            if (!Strings.isNullOrEmpty(modifyCarrierInfoBO.getModel()))
                if (!RegexUtil.check(RegexUtil.REGEX_UNICODECHAR, modifyCarrierInfoBO.getModel()))
                    throw new BaseException("生产厂商不合法");

//            Wrapper<CarrierInfo> carrierInfoWrapper = new EntityWrapper<>();
//            carrierInfoWrapper.ne("id", modifyCarrierInfoBO.getId());
//            carrierInfoWrapper.eq("driver_id", modifyCarrierInfoBO.getDriverId());
//            List<CarrierInfo> carrierInfoList = selectList(carrierInfoWrapper);
//            if (!CollectionUtils.isEmpty(carrierInfoList))
//                throw new BaseException("司机已被绑定");

            // 更新牵引车基础信息
            CarrierInfo carrierInfo = new CarrierInfo();
            BeanUtils.copyProperties(modifyCarrierInfoBO, carrierInfo);
            Long lspId = lspInfoService.getLspIdByTenantId(modifyCarrierInfoBO.getTenantId());
            carrierInfo.setLspId(lspId);
            if (!Objects.isNull(carrierInfo)) {
                Integer authStatus = carrierInfo.getAuthStatus();
                if (authStatus == AuthStatusEnum.CERTIFICATION.getCode()) {
                    throw new BaseException(-1, "该牵引车已经认证，请取消认证后再进行修改");
                }
            }
            this.updateById(carrierInfo);
            // 查询司机是否已经绑定牵引车
//            Wrapper<CarrierInfo> driverCarrierEntity = new EntityWrapper<>();
//            driverCarrierEntity.eq("driver_id", modifyCarrierInfoBO.getDriverId());
//            List<CarrierInfo> driverCarrierList = carrierInfoMapper.selectList(driverCarrierEntity);
//            if (driverCarrierList.size() > 1) {
//                throw new BaseException(CarrierEnum.DRIVER_EXIST.getCode(), CarrierEnum.DRIVER_EXIST.getText());
//            }

            // 查询牵引车下的证照
            Wrapper<CarrierLicense> carrierLicenseEntity = new EntityWrapper<>();
            carrierLicenseEntity.eq("carrier_id", carrierInfo.getId());
            List<CarrierLicense> selectCarrierLicenseList = carrierLicenseService.selectList(carrierLicenseEntity);
            // 前端传送的证照
            List<ModifyCarrierLicenseBO> toCarrierLicenseList = modifyCarrierInfoBO.getModifyCarrierLicenseBOList();

            if (CollectionUtils.isEmpty(selectCarrierLicenseList)) {
                //原来没有证照
                toCarrierLicenseList.forEach(modifyCarrierLicenseBO -> {
                    CarrierLicense carrierLicense = new CarrierLicense();
                    BeanUtils.copyProperties(modifyCarrierLicenseBO, carrierLicense);
                    carrierLicense.setCarrierId(carrierInfo.getId());
                    carrierLicenseService.insert(carrierLicense);
                });
            } else {
                toCarrierLicenseList.forEach(modifyCarrierLicenseBO -> {
                    CarrierLicense license = new CarrierLicense();
                    BeanUtils.copyProperties(modifyCarrierLicenseBO, license);
                    license.setId(getLicenseByIdOrType(modifyCarrierLicenseBO, modifyCarrierInfoBO.getId()).getId());
                    if (Objects.isNull(license.getId())) {
                        //新增
                        license.setCarrierId(carrierInfo.getId());
                        carrierLicenseService.insert(license);
                    } else {
                        //更新
                        carrierLicenseService.updateById(license);
                    }
                });
            }

            // 前端传送的卡片信息
            List<ModifyCarrierCardBO> toCarrierCardList = modifyCarrierInfoBO.getModifyCarrierCardBOList();
            // 前端新增的卡片
            List<CarrierCard> addCarrierCardList = new ArrayList<>();

            // 更新牵引车卡片信息
            for (ModifyCarrierCardBO modifyCarrierCardBO : toCarrierCardList) {

                CarrierCard carrierCard = new CarrierCard();
                BeanUtils.copyProperties(modifyCarrierCardBO, carrierCard);
                carrierCard.setCarrierId(carrierInfo.getId());

                if (carrierCard.getId() == null) {
                    addCarrierCardList.add(carrierCard);
                } else {
                    carrierCardService.updateById(carrierCard);
                }
            }

            if (!CollectionUtils.isEmpty(addCarrierCardList)) {
                // 批量新增牵引车卡片信息
                carrierCardService.insertOrUpdateBatch(addCarrierCardList);
            }
        } catch (BaseException e) {
            throw e;
        } catch (Exception ex) {
            throw new BaseException(-1, "操作异常请重试");
        }

    }

    @Override
    public void checkModifyData(ModifyCarrierInfoBO modifyCarrierInfoBO, String operate) {

        if (modifyCarrierInfoBO == null || StringUtils.isEmpty(operate))
            return;
        if (operate.equals("modify")) {
            if (modifyCarrierInfoBO.getId() == null)
                return;
            Wrapper<CarrierInfo> plateCarrierEntity = new EntityWrapper<>();
            plateCarrierEntity.eq("plate", modifyCarrierInfoBO.getPlate().trim())
                    .ne("id", modifyCarrierInfoBO.getId())
                    .ne("is_delete", TableStatusEnum.STATUS_1.getCode());
            List<CarrierInfo> plateCarrierList = baseMapper.selectCarrierNoTenant(plateCarrierEntity);
            if (!CollectionUtils.isEmpty(plateCarrierList)) {
                throw new BaseException(CarrierEnum.PLATE_EXIST.getCode(), "该车牌号已被使用");
            }
        }
        if (modifyCarrierInfoBO.getPlate() == null)
            return;
        if (operate.equals("insert")) {
            Wrapper<CarrierInfo> plateCarrierEntity = new EntityWrapper<>();
            plateCarrierEntity.eq("plate", modifyCarrierInfoBO.getPlate().trim())
                    .ne("is_delete", TableStatusEnum.STATUS_1.getCode());
            List<CarrierInfo> plateCarrierList = baseMapper.selectCarrierNoTenant(plateCarrierEntity);
            if (!CollectionUtils.isEmpty(plateCarrierList)) {
                throw new BaseException(CarrierEnum.PLATE_EXIST.getCode(), "该车牌号已被使用");
            }
        }
    }

    @Override
    public Page<CarrierDetailVO> getCarrierByLsp(Page<CarrierDetailVO> page, String authorization) {
        if (Objects.isNull(page.getCondition().get("lspId")) || Strings.isNullOrEmpty(page.getCondition().get("lspId").toString()))
            throw new BaseException("未获取到对应承运商");
        Long lspId = Long.parseLong(page.getCondition().get("lspId").toString());
        Wrapper<CarrierInfo> ew = new EntityWrapper<>();
        ew.eq("lsp_id", page.getCondition().get("lspId"));
        if (Objects.nonNull(page.getCondition().get("plate"))) {
            ew.like("plate", page.getCondition().get("plate").toString());
        }
        if (!Objects.isNull(page.getCondition().get("isAuth"))) {
            if ("1".equals(page.getCondition().get("isAuth").toString())) {
                ew.eq("auth_status", AuthStatusEnum.CERTIFICATION.getCode());
            } else {
                ew.eq("auth_status", AuthStatusEnum.UNAUTHORIZED.getCode());
            }
        }
        ew.eq("is_delete", TableStatusEnum.STATUS_0.getCode());
        Page<CarrierInfo> carrierInfoList = new Page<>(page.getCurrent(), page.getSize());
        carrierInfoList = this.selectPage(carrierInfoList, ew);
        BeanUtils.copyProperties(carrierInfoList, page);
        if (!CollectionUtils.isEmpty(carrierInfoList.getRecords())) {
            // 查询承运商信息
            LspInfo lspInfo = lspInfoService.selectById(lspId);
            List<CarrierDetailVO> carrierDetailVOList = new ArrayList<>();
            for (CarrierInfo carrierInfo : carrierInfoList.getRecords()) {
                CarrierDetailVO carrierDetailVO = new CarrierDetailVO();
                BeanUtils.copyProperties(carrierInfo, carrierDetailVO);
                if (!Strings.isNullOrEmpty(carrierDetailVO.getCreator())) {
                    AccountVO accountVO = uaaUtil.getAccountById(carrierDetailVO.getCreator(), authorization);
                    if (Objects.nonNull(accountVO)) {
                        carrierDetailVO.setCreator(accountVO.getIdentifier());
                    }
                }
                if (lspInfo != null) {
                    carrierDetailVO.setLspName(lspInfo.getName());
                }
                carrierDetailVOList.add(carrierDetailVO);
            }
            page.setRecords(carrierDetailVOList);
        }
        return page;
    }

    /**
     * 获取承运商下  认证且绑定挂车/司机的牵引车信息
     */
    @Override
    public Page<CarrierDetailVO> queryCarrierByLsp(Page<CarrierDetailVO> page, String authorization) {
        if (Objects.isNull(page.getCondition().get("lspId")) ||
                Strings.isNullOrEmpty(page.getCondition().get("lspId").toString()))
            throw new BaseException("LSP id 不能为空");
        long lspId = Long.parseLong(page.getCondition().get("lspId").toString());
        // 查询承运商信息
        LspInfo lspInfo = lspInfoService.selectById(lspId);
        if (lspInfo == null) {
            throw new BaseException("未查询到LSP id:" + lspId + "的承运商信息");
        }
        Wrapper<CarrierInfo> ew = new EntityWrapper<>();
        ew.eq("lsp_id", page.getCondition().get("lspId"));
        if (Objects.nonNull(page.getCondition().get("plate"))) {
            ew.like("plate", page.getCondition().get("plate").toString());
        }
        if (!Objects.isNull(page.getCondition().get("isAuth"))) {
            if ("1".equals(page.getCondition().get("isAuth").toString())) {
                ew.eq("auth_status", AuthStatusEnum.CERTIFICATION.getCode());
            } else {
                ew.eq("auth_status", AuthStatusEnum.UNAUTHORIZED.getCode());
            }
        }

        Page<CarrierInfo> carrierInfoList = selectPage(new Page<>(page.getCurrent(), page.getSize()), ew);
        if (!CollectionUtils.isEmpty(carrierInfoList.getRecords())) {
            List<CarrierDetailVO> carrierDetailVOList = new ArrayList<>();
            for (CarrierInfo carrierInfo : carrierInfoList.getRecords()) {
                CarrierDetailVO carrierDetailVO = new CarrierDetailVO();
                BeanUtils.copyProperties(carrierInfo, carrierDetailVO);

                //查询绑定司机信息
                EntityWrapper<DriverCarrierBind> driverBdEW = new EntityWrapper<>();
                driverBdEW.eq("carrier_id", carrierInfo.getId())
                        .orderBy("id", false);
                DriverCarrierBind carrierBind = driverCarrierBindService.selectOne(driverBdEW);
                if (carrierBind == null) {
                    continue;
                }
                Driver driver = driverService.selectById(carrierBind.getDriverId());
                if (driver == null) {
                    continue;
                }
                Wrapper<FleetBind> fleetBindWrapper = new EntityWrapper<>();
                fleetBindWrapper.eq("resource_id", carrierInfo.getId()).eq("resource_type", "01");
                FleetBind fleetBind = fleetBindService.selectOne(fleetBindWrapper);
                if (Objects.nonNull(fleetBind)) {
                    Fleet fleet = fleetService.selectById(fleetBind.getFleetId());
                    carrierDetailVO.setFleetId(String.valueOf(fleetBind.getFleetId()));
                    carrierDetailVO.setFleetName(fleet.getFleetName());
                }
                carrierDetailVO.setDriverId(driver.getId());
                carrierDetailVO.setDriverName(driver.getName());
                carrierDetailVO.setDriverMobile(driver.getMobile());
                if (!Strings.isNullOrEmpty(carrierDetailVO.getCreator())) {
                    AccountVO accountVO = uaaUtil.getAccountById(carrierDetailVO.getCreator(), authorization);
                    if (Objects.nonNull(accountVO)) {
                        carrierDetailVO.setCreator(accountVO.getIdentifier());
                    }
                }
                carrierDetailVO.setLspName(lspInfo.getName());
                carrierDetailVOList.add(carrierDetailVO);
            }
            page.setRecords(carrierDetailVOList);
        }
        return page;
    }


    @Override
    public List<String> discontinuatCarrier(Long[] carrierIds) throws BaseException {
        List<String> msgs = Lists.newArrayList();
        if (ArrayUtils.isEmpty(carrierIds)) {
            throw new BaseException("牵引车的ID为空");
        }
        for (Long id : carrierIds) {
            CarrierInfo carrierInfo = this.selectById(id);
            if (StatusEnum.DISCONTINUAT.getCode().equals(carrierInfo.getStatus())) {
                msgs.add("牵引车:" + carrierInfo.getPlate() + ":已处于停用状态");
                continue;
            }
            baseMapper.updateStatus(StatusEnum.DISCONTINUAT.getCode(), id);
        }
        return msgs;
    }

    @Override
    public List<String> enableCarrier(Long[] carrierIds) throws BaseException {

        List<String> msgs = Lists.newArrayList();
        if (ArrayUtils.isEmpty(carrierIds)) {
            throw new BaseException("牵引车的ID为空");
        }
        for (Long id : carrierIds) {
            CarrierInfo carrierInfo = this.selectById(id);
            if (StatusEnum.ENABLE.getCode().equals(carrierInfo.getStatus())) {
                msgs.add("牵引车:" + carrierInfo.getPlate() + ":已处于启用状态");
                continue;
            }

            if (AuthStatusEnum.UNAUTHORIZED.getCode().equals(carrierInfo.getAuthStatus())) {
                msgs.add("牵引车:" + carrierInfo.getPlate() + ":未认证,无法启用");
                continue;
            }

            baseMapper.updateStatus(StatusEnum.ENABLE.getCode(), id);
        }
        return msgs;
    }

    @Override
    public void batchUpdateStatusByLspId(Integer authStatus, Integer status, List<Long> lspIdList) throws BaseException {
        try {
            baseMapper.batchUpdateStatusByLspId(authStatus, status, lspIdList);
        } catch (Exception ex) {
            throw new BaseException(-1, ex.getMessage());
        }
    }

    @Override
    public List<CarrierInfo> getListsByLspId(Long lspId) {
        EntityWrapper<CarrierInfo> ew = new EntityWrapper<>();
        ew.where("lsp_id = {0}", lspId);
        List<CarrierInfo> list = this.selectList(ew);
        return list;
    }


    @Transactional(rollbackFor = Exception.class)
    public void carrierAuth(Long carrierId, String authorization) throws BaseException {
        CarrierInfo needAuthCarrier = this.selectById(carrierId);
        if (Objects.isNull(needAuthCarrier)) {
            throw new BaseException("牵引车不存在");
        }
        if (needAuthCarrier.getAuthStatus().equals(AuthStatusEnum.CERTIFICATION.getCode())) {
            throw new BaseException("牵引车:" + needAuthCarrier.getPlate() + ":" + "已经是认证状态，无需重复进行认证");
        }

        //更新认证
        CarrierInfo authInfo = new CarrierInfo();
        authInfo.setId(needAuthCarrier.getId());
        authInfo.setAuthStatus(Integer.valueOf(TableStatusEnum.STATUS_1.getCode()));
        authInfo.setStatus(Integer.valueOf(TableStatusEnum.STATUS_1.getCode()));
        authInfo.setGmtUpdate(new Date());
        baseMapper.updateById(authInfo);
        //认证日志
        JwtAccountVO jwtAccountVO = AccountUtil.getAccountInfoFromSecurityContext();
        CarrierAuditLog carrierAuditLog = new CarrierAuditLog();
        BeanUtils.copyProperties(authInfo, carrierAuditLog);
        carrierAuditLog.setCarrierId(carrierId);
        carrierAuditLog.setAuditResult(1);
        if (Objects.nonNull(jwtAccountVO)) {
            carrierAuditLog.setTenantId(Long.parseLong(jwtAccountVO.getTenantId()));
            carrierAuditLog.setCreator(jwtAccountVO.getAccountId());
        }
        iCarrierAuditLogService.insert(carrierAuditLog);
        // 推送OTM
        carrierAndTrailerToOtm(carrierId, IntegrationEnum.ISACTIVE.getCode());
        //中联下面车队推送erp
        carrierToERP(authorization, carrierId);
    }

    @Override
    public void carrierToERP(String authorization, Long carrierId) {
        if (TableStatusEnum.STATUS_Y.getCode().equals(properties.getPushDataToERP())) {
            if (carrierId != null) {
                List<WeChatVehicle> vehicles = baseMapper.selectVehicleByCarrierIdOrTrailerIdNoTenant(carrierId, null);
                if (!CollectionUtils.isEmpty(vehicles)) {
                    WeChatVehicle weChatVehicle = vehicles.get(0);
                    EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
                    ew.eq("resource_id", weChatVehicle.getId())
                            .eq("resource_type", TableStatusEnum.STATUS_01.getCode())
                            .orderBy("id", false);
                    List<FleetBindVO> carrierFleetS = fleetBindService.queryBindCarrierNoTenant(ew);
                    CarrierToErpDTO carrierToErpDTO = new CarrierToErpDTO();
                    carrierToErpDTO.setId(weChatVehicle.getId());
                    carrierToErpDTO.setDriverId(weChatVehicle.getDriverId());
                    carrierToErpDTO.setDriverName(weChatVehicle.getDriverName());
                    carrierToErpDTO.setDriverPhone(weChatVehicle.getDriverMobile());
                    if (!CollectionUtils.isEmpty(carrierFleetS)) {
                        carrierToErpDTO.setFleetId(carrierFleetS.get(0).getFleetId());
                        carrierToErpDTO.setFleetName(carrierFleetS.get(0).getFleetName());

                        String fleetTypeId = carrierFleetS.get(0).getFleetTypeId();

                        if (TableStatusEnum.STATUS_2.getCode().equals(fleetTypeId)) {
                            carrierToErpDTO.setProperty(TableStatusEnum.STATUS_3.getCode());
                        } else if (TableStatusEnum.STATUS_1.getCode().equals(fleetTypeId)) {
                            carrierToErpDTO.setProperty(fleetTypeId);
                        } else if (!StringUtils.isEmpty(fleetTypeId)) {
                            carrierToErpDTO.setProperty(TableStatusEnum.STATUS_2.getCode());
                        }
                    } else {
                        carrierToErpDTO.setFleetId(Long.valueOf(TableStatusEnum.STATUS_0.getCode()));
                    }
                    carrierToErpDTO.setLspId(String.valueOf(weChatVehicle.getLspId()));
                    carrierToErpDTO.setLspName(weChatVehicle.getLspName());
                    carrierToErpDTO.setTrailerId(weChatVehicle.getTrailerId());
                    carrierToErpDTO.setPlate(weChatVehicle.getPlate());
                    TrailerInfo trailerInfo = trailerInfoService.selectByIdNoTenant(weChatVehicle.getTrailerId());
                    if (trailerInfo != null) {
                        carrierToErpDTO.setTrailerProper(trailerInfo.getTrailerProper());
                        carrierToErpDTO.setTransMode(DictionaryUtil.getTransMode(trailerInfo.getTrailerType()));
                    }

                    //牵引车增加油卡/路桥卡信息推送erp--油卡
                    EntityWrapper<CarrierCard> oilEW = new EntityWrapper<>();
                    oilEW.eq("carrier_id", weChatVehicle.getId())
                            .eq("card_type_code", TableStatusEnum.STATUS_CARD_100.getCode());
                    List<CarrierCard> oilCards = cardService.selectCardNoTenant(oilEW);
                    if (!CollectionUtils.isEmpty(oilCards)) {
                        carrierToErpDTO.setOilCardNo(oilCards.get(0).getCardSn());
                    }
                    // 路桥卡
                    EntityWrapper<CarrierCard> roadEW = new EntityWrapper<>();
                    roadEW.eq("carrier_id", weChatVehicle.getId())
                            .eq("card_type_code", TableStatusEnum.STATUS_CARD_200.getCode());
                    List<CarrierCard> roadCards = cardService.selectCardNoTenant(roadEW);
                    if (!CollectionUtils.isEmpty(roadCards)) {
                        carrierToErpDTO.setRoadCardNo(roadCards.get(0).getCardSn());
                    }
                    List<NameValuePair> headNamePairs = Lists.newArrayList();
                    headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
                    String erpJson = JSONObject.toJSONString(carrierToErpDTO);
                    LOGGER.info("CarrierToErp url:{} param:{} ", integrationUrl + carrierPushErpUrl, erpJson);
                    String result = null;
                    try {
                        RedisLogUtil.addSysLogs(SystemEnum.LSPM.getCode(),SystemEnum.INTEGRATION.getCode(),"carrier"+carrierToErpDTO.getId(), JSON.toJSONString(carrierToErpDTO),"/erp-api/carrierPushErp",1,1,null,isTest);
                        result = HttpClientUtil.postJson(integrationUrl + carrierPushErpUrl, headNamePairs, erpJson, socketTimeout);
                        LOGGER.info("CarrierToErp result {} ", result);
                    } catch (Exception e) {
                        LOGGER.error("CarrierToErp 连接超时失败 url:{} error:{} ", integrationUrl + carrierPushErpUrl, e);
                    }
                    if (StringUtils.isEmpty(result)) {
                        LOGGER.error("CarrierToErp 未响应 param:{}", erpJson);
                    }
                }
            }
        }
    }

    @Override
    public List<String> batchUpdateAuthStatusByIds(Long[] carrierIds, String authorization) {
        if (ArrayUtils.isEmpty(carrierIds)) {
            throw new BaseException("请选择需要认证的牵引车");
        }
        List<String> errorMsg = new ArrayList<>();
        for (Long carrierId : carrierIds) {
            try {
                carrierAuth(carrierId, authorization);
            } catch (BaseException e) {
                errorMsg.add(e.getMessage());
            } catch (Exception e) {
                LOGGER.error(e.getMessage());
                errorMsg.add("系统处理异常");
            }
        }
        return errorMsg;
    }

    private boolean licenseValid(Long carrierId) throws BaseException {
        EntityWrapper<CarrierLicense> ew = new EntityWrapper<>();
        ew.eq("carrier_id", carrierId);
        List<CarrierLicense> carrierLicenses = carrierLicenseService.selectList(ew);
        List<LicenseTypeVo> licenseTypes = mdmUtil.listLicenseTypeBySubject("04");
        for (CarrierLicense license : carrierLicenses) {
            LicenseTypeVo licenseType = getLicenseType(license.getLicenseTypeId(), licenseTypes);
            if (Objects.nonNull(licenseType)) {
                if (StringUtils.isEmpty(license.getLicenseId())) throw new BaseException(
                        licenseType.getTypeValue() + "编码为空");
//                if (Objects.isNull(license.getGmtReg())) throw new BaseException(licenseType.getTypeValue()
//                        + "生效日期为空");
//                if (!licenseType.getIsPerm().equals(1) && Objects.isNull(license.getGmtOverdue())) {
//                    throw new BaseException(licenseType.getTypeValue() + "失效日期为空！");
//                }
                Wrapper<CarrierLicenseAttach> ewAttach = new EntityWrapper<>();
                ewAttach.eq("license_id", license.getId()).and().eq("carrier_id", license.getCarrierId());
                if (carrierLicenseAttachService.selectCount(ewAttach) == 0) {
                    throw new BaseException(licenseType.getTypeValue() + "附件为空！");
                }
            } else {
                throw new BaseException("牵引车证照类型有误");
            }

        }
        return true;
    }

    private LicenseTypeVo getLicenseType(Long licenseTypeId, List<LicenseTypeVo> licenseTypes) {
        LicenseTypeVo newLicenseType = null;
        Optional<LicenseTypeVo> optional = licenseTypes.stream().filter(licenseType -> licenseType.getId().equals(licenseTypeId)).findFirst();
        if (optional.isPresent()) {
            newLicenseType = optional.get();
        }
        return newLicenseType;
    }

    @Transactional
    @Override
    public void batchUpdateCancelAuthStatusByIds(Long[] carrierIds) throws BaseException {
        if (ArrayUtils.isEmpty(carrierIds)) {
            throw new BaseException("牵引车的ID为空");
        }
        List<Long> idList = Arrays.asList(carrierIds);
        idList.forEach(id -> {
            CarrierInfo carrierInfo = this.selectById(id);
            if (!Objects.isNull(carrierInfo)) {
                if (carrierInfo.getAuthStatus().intValue() == AuthStatusEnum.UNAUTHORIZED.getCode().intValue()) {
                    throw new BaseException("牵引车车牌号：" + carrierInfo.getPlate() + "已经取消认证，无需重复取消认证");
                }
            }
        });

        baseMapper.batchUpdateAuthStatusByIds(AuthStatusEnum.UNAUTHORIZED.getCode(), StatusEnum.DISCONTINUAT.getCode(), idList);

        //写入日志表
        iCarrierAuditLogService.batchInsertLog(idList, 0);

        idList.forEach(id -> {
            if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
                WeChatVehicle weChatVehicle = baseMapper.selectVehicleByCarrierIdOrTrailerId(id, null);

                if (!StringUtils.isEmpty(weChatVehicle.getTrailerTypeId())) {
                    String trailerTypeName = mdmUtil.getTransportTypeByCode(weChatVehicle.getTrailerTypeId()).getValue();
                    weChatVehicle.setTrailerTypeName(integrationUtil.getTrailerTypeName(trailerTypeName));
                }
                VehicleDTO vehicleDTO = new VehicleDTO();
                // 设置车队类型-自有
                toOtmSetFleetType(id, null, weChatVehicle);
                BeanUtils.copyProperties(weChatVehicle, vehicleDTO);

                if (!StringUtils.isEmpty(weChatVehicle.getTractorType()) && weChatVehicle.getTractorType().equals("20")) {
                    vehicleDTO.setTrailerTypeName("救援车");
                    vehicleDTO.setIsActive(IntegrationEnum.NOACTIVE.getCode());
                    integrationUtil.exportVehicleToOTM(vehicleDTO);
                } else if (Objects.nonNull(weChatVehicle.getTrailerAuthStatus()) && weChatVehicle.getTrailerAuthStatus() == 0) {
                    vehicleDTO.setIsActive(IntegrationEnum.NOACTIVE.getCode());
                    integrationUtil.exportVehicleToOTM(vehicleDTO);
                }
            }
        });
    }

    @Override
    public void toOtmSetFleetType(Long carrierId, Long trailerId, WeChatVehicle weChatVehicle) {
        FleetCarId fleetCar = fleetService.getNewFleetByCarrierIdOrTrailerIdNoTenant(carrierId, trailerId);
        if (fleetCar != null) {
            if (TableStatusEnum.STATUS_1.getCode().equals(String.valueOf(fleetCar.getFleetTypeId()))) {
                weChatVehicle.setFleetTypeId("y");
            }
        } else {
            List<FleetCarId> fleetCarIds = fleetService.getOldFleetByCarrierIdOrTrailerIdNoTenant(carrierId, trailerId);
            if (fleetCarIds.size() > 0) {
                if (TableStatusEnum.STATUS_1.getCode().equals(String.valueOf(fleetCarIds.get(0).getFleetTypeId()))) {
                    weChatVehicle.setFleetTypeId("y");
                }
            }
        }
    }

    @Override
    public List<WeChatVehicle> selectVehicleByCarrierIdOrTrailerIdNoTenant(Long carrierId, Long trailerId) {
        return baseMapper.selectVehicleByCarrierIdOrTrailerIdNoTenant(carrierId, trailerId);
    }

    @Override
    public CarrierInfoLineVO getCarrierInfoByPlate(String plate) {
        return baseMapper.getVehicleByPlateNotenant(plate);
    }


    @Override
    public List<String> authedCarrierPlate() {

        Wrapper<CarrierInfo> carrierInfoWrapper = new EntityWrapper<>();
        carrierInfoWrapper.eq("auth_status", AuthStatusEnum.CERTIFICATION.getCode());
        List<CarrierInfo> carrierInfoList = selectList(carrierInfoWrapper);

        if (!CollectionUtils.isEmpty(carrierInfoList)) {
            List<String> plateList = carrierInfoList.stream().map(CarrierInfo::getPlate).collect(Collectors.toList());
            return plateList;
        }

        return null;
    }

    @Override
    public List<String> authedTenantPlate(Long tenantId) {
        Wrapper<CarrierInfo> carrierInfoWrapper = new EntityWrapper<>();
        carrierInfoWrapper.eq("auth_status", AuthStatusEnum.CERTIFICATION.getCode());
        carrierInfoWrapper.eq("tenant_id", tenantId);
        List<CarrierInfo> carrierInfoList = selectList(carrierInfoWrapper);

        if (!CollectionUtils.isEmpty(carrierInfoList)) {
            List<String> plateList = carrierInfoList.stream().map(CarrierInfo::getPlate).collect(Collectors.toList());
            return plateList;
        }

        return null;
    }

    @Override
    public List<Long> selectIdByLspIds(List<Long> lspIdList) {
        return this.baseMapper.selectIdByLspIds(lspIdList);
    }

    @Override
    public void batchUpdateAuthStatusByIds(Integer authStatus, Integer status, List<Long> idList) {
        baseMapper.batchUpdateAuthStatusByIds(authStatus, status, idList);
    }

    @Override
    public Page<CarrierTrailerBO> queryPageCarrierTrailer(Page<CarrierTrailerBO> page, String authorization) {
        Map<String, Object> condition = page.getCondition();
        Wrapper<CarrierTrailerBO> ew = buildCarTraCondition(condition);
        List<CarrierTrailerBO> carrierTrailerBOS = baseMapper.selectPageCarrierTrailer(page, ew);
        if (!CollectionUtils.isEmpty(carrierTrailerBOS)) {
            for (CarrierTrailerBO carrierTrailerBO : carrierTrailerBOS) {
                if (Objects.nonNull(carrierTrailerBO.getTrailerType())) {
                    List<TransportationTypeVO> allServiceType = mdmUtil.getAllFleetTransportType();
                    String serviceTypeName = carrierTrailerBO.getTrailerType();
                    for (TransportationTypeVO transportationTypeVO :
                            allServiceType) {
                        serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
                    }
                    carrierTrailerBO.setTrailerTypeName(serviceTypeName);
                }
            }
        }
        page.setRecords(carrierTrailerBOS);
        return page;
    }

    /**
     * 得到可用挂车
     *
     * @param id           牵引车ID
     * @param trailerPlate 挂车车牌
     */
    @Override
    public List<TrailerCarrierBO> queryUsableTrailer(Long id, String trailerPlate, String authorization) {
        CarrierInfo carrierInfo = this.selectById(id);
        if (Objects.isNull(carrierInfo)) throw new BaseException("牵引车不存在");
        Long lspId = carrierInfo.getLspId();
        Long tenantId = carrierInfo.getTenantId();

        Wrapper<TrailerCarrierBO> ew = new EntityWrapper<>();

        if (Objects.isNull(tenantId)) {
            ew.isNull("tenant_id");//租户为空
        } else {
            ew.eq("tenant_id", tenantId);
        }
        if (Objects.isNull(lspId)) {
            ew.isNull("lsp_id");//承运商为空
        } else {
            ew.eq("lsp_id", lspId);
        }
        ew.like("plate", trailerPlate);
        ew.isNull("carrier_id"); //牵引车为空
        return trailerInfoService.listUsableTrailer(ew);
    }

    @Override
    public boolean bingTrailer(Long carrierId, Long trailerId, Long tenantId, String authorization) {
        boolean bingTrailer = carrierTrailerBindService.bindCarrierTrailer(carrierId, trailerId, tenantId);
        carrierAndTrailerToOtm(carrierId, IntegrationEnum.ISACTIVE.getCode());
        Wrapper<FleetBind> fleetBindEw = new EntityWrapper<>();
        carrierInfoService.carrierToERP(authorization, carrierId);
        trailerInfoService.authTrailerToERP(trailerId, authorization);
        return bingTrailer;
    }

    @Override
    public boolean unbingTrailer(Long carrierId, Long trailerId, String authorization) {
        boolean unbingTrailer = carrierTrailerBindService.unbindCarrierTrailer(carrierId, trailerId);
        carrierAndTrailerToOtm(carrierId, IntegrationEnum.NOACTIVE.getCode());
        carrierInfoService.carrierToERP(authorization, carrierId);
        trailerInfoService.authTrailerToERP(trailerId, authorization);
        return unbingTrailer;
    }

    @Override
    public void carrierAndTrailerToOtm(Long carrierId, String isAtcive) {
        if (IntegrationEnum.EXPORT.getCode().equals(IntegrationUtil.getIntegrationToOtm())) {
            //获取中联下面的所有管理员账号
            EntityWrapper<FleetBindVO> ew = new EntityWrapper<>();
            ew.eq("resource_id", carrierId)
                    .eq("resource_type", TableStatusEnum.STATUS_01.getCode())
                    .orderBy("id", false);
            List<FleetBindVO> fleetCarrierVOS = fleetBindService.queryBindCarrierNoTenant(ew);

            VehicleDTO vehicleDTO = new VehicleDTO();
            // 设置车队类型-自有
            List<WeChatVehicle> weChatVehicles = baseMapper.selectVehicleByCarrierIdOrTrailerIdNoTenant(carrierId, null);
            if (!CollectionUtils.isEmpty(weChatVehicles)) {
                WeChatVehicle weChatVehicle = weChatVehicles.get(0);
                toOtmSetFleetType(carrierId, null, weChatVehicle);
                if (!CollectionUtils.isEmpty(fleetCarrierVOS)) {
                    weChatVehicle.setFleetId(fleetCarrierVOS.get(0).getFleetId());
                } else {
                    weChatVehicle.setFleetId(weChatVehicle.getLspId());
                }
                if (!StringUtils.isEmpty(weChatVehicle.getDriverId())) {
                    Wrapper<DriverLicense> driverLicenseWrapper = new EntityWrapper<>();
                    driverLicenseWrapper.eq("driver_id", weChatVehicle.getDriverId());
                    driverLicenseWrapper.eq("license_type_id", TableStatusEnum.STATUS_1.getCode());
                    DriverLicense driverLicense = driverLicenseService.selectOneNoTenant(driverLicenseWrapper);
                    if (Objects.nonNull(driverLicense) && !StringUtils.isEmpty(driverLicense.getLicenseId())) {
                        weChatVehicle.setIdCard(driverLicense.getLicenseId());
                    }
                }
                if (Objects.isNull(weChatVehicle.getTrailerAuthStatus()) && weChatVehicle.getAuthStatus() == 1) {
                    if ("20".equals(weChatVehicle.getTractorType())) {
                        BeanUtils.copyProperties(weChatVehicle, vehicleDTO);
                        vehicleDTO.setTrailerTypeName("救援车");
                        vehicleDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
                        integrationUtil.exportVehicleToOTM(vehicleDTO);
                    }
                } else if (Objects.nonNull(weChatVehicle.getTrailerAuthStatus())
                        && weChatVehicle.getTrailerAuthStatus() == 1
                        && weChatVehicle.getAuthStatus() == 1
                        && !StringUtils.isEmpty(weChatVehicle.getTrailerTypeId())) {
                    String trailerTypeName = mdmUtil.getTransportTypeByCode(weChatVehicle.getTrailerTypeId()).getValue();
                    weChatVehicle.setTrailerTypeName(integrationUtil.getTrailerTypeName(trailerTypeName));
                    BeanUtils.copyProperties(weChatVehicle, vehicleDTO);
                    vehicleDTO.setIsActive(IntegrationEnum.ISACTIVE.getCode());
                    //fix 2019-1-15增加车辆属性
                    vehicleDTO.setVehicleProper(weChatVehicle.getTrailerProper()); //车辆属性
                    integrationUtil.exportVehicleToOTM(vehicleDTO);
                } else if (isAtcive.equals(IntegrationEnum.NOACTIVE.getCode())) {
                    BeanUtils.copyProperties(weChatVehicle, vehicleDTO);
                    vehicleDTO.setTrailerTypeName("单车");
                    vehicleDTO.setIsActive(IntegrationEnum.NOACTIVE.getCode());
                    //fix 2019-1-15增加车辆属性
                    vehicleDTO.setVehicleProper(weChatVehicle.getTrailerProper());//车辆属性
                    integrationUtil.exportVehicleToOTM(vehicleDTO);
                }
            }

        }
    }

    @Override
    public List<CarrierDriverBO> listUsableCarrier(Wrapper<CarrierDriverBO> ew) {
        return baseMapper.listUsableCarrier(ew);
    }

    @Override
    public List<String> deleteByIds(Long[] carrierIds) {
        List<String> msgs = new ArrayList<>();
        for (Long id : carrierIds) {
            String msg = "";
            CarrierInfo carrierInfo = this.selectById(id);
            if (AuthStatusEnum.CERTIFICATION.getCode().equals(carrierInfo.getAuthStatus())) {
                msg = "牵引车:" + carrierInfo.getPlate() + ":已认证无法删除";
                msgs.add(msg);
                continue;
            }

            Wrapper<CarrierTrailerBind> ewCarTrailer = new EntityWrapper<>();
            ewCarTrailer.eq("carrier_id", id);
            if (carrierTrailerBindService.selectCount(ewCarTrailer) > 0) {
                msg = "牵引车:" + carrierInfo.getPlate() + ":已经与挂车绑定，无法删除";
                msgs.add(msg);
                continue;
            }

            Wrapper<DriverCarrierBind> ewDriverCar = new EntityWrapper<>();
            ewDriverCar.eq("carrier_id", id);
            if (driverCarrierBindService.selectCount(ewDriverCar) > 0) {
                msg = "牵引车:" + carrierInfo.getPlate() + ":已经与司机绑定，无法删除";
                msgs.add(msg);
                continue;
            }

            this.deleteById(id);
        }

        return msgs;
    }

    private Wrapper<CarrierTrailerBO> buildCarTraCondition(Map<String, Object> condition) {

        Wrapper<CarrierTrailerBO> ew = new EntityWrapper<>();
        if (!Objects.isNull(condition)) {

            //牵引车车牌
            if (condition.containsKey("plate") && !StringUtils.isEmpty(condition.get("plate"))) {
                ew.like("plate", condition.get("plate").toString().trim());
            }

            //承运商名称
            if (condition.containsKey("lspName") && !StringUtils.isEmpty(condition.get("lspName"))) {
                ew.like("lspName", condition.get("lspName").toString().trim());
            }
            //承运商名称
            if (condition.containsKey("tenantId") && !StringUtils.isEmpty(condition.get("tenantId"))) {
                ew.eq("tenant_id", condition.get("tenantId").toString().trim());
            }

            //挂车车牌
            if (condition.containsKey("trailerPlate") && !StringUtils.isEmpty(condition.get("trailerPlate"))) {
                ew.like("trailerPlate", condition.get("trailerPlate").toString().trim());
            }

            //牵引车状态
            if (condition.containsKey("status") && !StringUtils.isEmpty(condition.get("status"))) {
                ew.eq("status", condition.get("status").toString().trim());
            }

            //牵引审核状态
            if (condition.containsKey("authStatus") && !StringUtils.isEmpty(condition.get("authStatus"))) {
                ew.eq("auth_status", condition.get("authStatus").toString().trim());
            }

            //挂车状态
            if (condition.containsKey("trailerStatus") && !StringUtils.isEmpty(condition.get("trailerStatus"))) {
                ew.eq("trailerStatus", condition.get("trailerStatus").toString().trim());
            }

            //挂车认证状态
            if (condition.containsKey("trailerAuthStatus") && !StringUtils.isEmpty(condition.get("trailerAuthStatus"))) {
                ew.eq("trailerAuthStatus", condition.get("trailerAuthStatus").toString().trim());
            }
            if (condition.containsKey("fleetFlag")
                    && !StringUtils.isEmpty(condition.containsKey("fleetFlag"))) {
                // 车队
                if (condition.containsKey("fleetId") && !StringUtils.isEmpty(condition.get("fleetId"))) {
                    String fleetId = (String) condition.get("fleetId");
                    List<String> fleetIds = Arrays.asList(fleetId.split(","));
                    ew.in("new_FleetId", fleetIds);
                } else {
                    throw new BaseException("非车队管理员不能进行该操作");
                }
            }
            if (condition.containsKey("fleetName") && !StringUtils.isEmpty(condition.get("fleetName"))) {
                ew.eq("fleet_name", condition.get("fleetName").toString().trim());
            }
        }
        ew.orderBy("gmt_create", false);
        return ew;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean changeLspAndRemoveRelation(Long[] carrierIds,
                                              Long lspId,
                                              Integer isAllTransfer,
                                              String authorization) {
        if (carrierIds == null
                || carrierIds.length == 0
                || StringUtils.isEmpty(lspId)
                || StringUtils.isEmpty(isAllTransfer)) {
            throw new BaseException("请选择需要转移的车辆");
        }
        //转移牵引车
        // 1.取消牵引车与原来车队的绑定关系;
        // 2.判断是否转移挂车,
        // 否:取消牵引车和司机及挂车的绑定关系；
        //和挂车司机一起转移:不取消原来车辆和司机/挂车的绑定关系
        //3.关系同步推送ERP

        //更新牵引车
        LspInfo lspInfo = lspInfoService.selectById(lspId);
        Arrays.stream(carrierIds).forEach(carrierId -> {
            CarrierInfo carrierInfo = new CarrierInfo();
            carrierInfo.setTenantId(lspInfo.getTenantId());
            carrierInfo.setLspId(lspInfo.getId());
            carrierInfo.setId(carrierId);
            baseMapper.updateById(carrierInfo);
            fleetBindService.deleteFleetBind(carrierId, TableStatusEnum.STATUS_01.getCode());
            Wrapper<CarrierTrailerBind> ctbEW = new EntityWrapper<>();
            ctbEW.eq("carrier_id", carrierId)
                    .orderBy("id", false);
            CarrierTrailerBind ctb = carrierTrailerBindService.selectOne(ctbEW);
            Wrapper<DriverCarrierBind> driverCarrierBindWrapper = new EntityWrapper<>();
            driverCarrierBindWrapper.eq("carrier_id", carrierId);
            DriverCarrierBind dcb = driverCarrierBindService.selectOne(driverCarrierBindWrapper);
            if (isAllTransfer == 1) {
                if (ctb != null) {
                    ctb.setTenantId(lspInfo.getTenantId());
                    carrierTrailerBindService.update(ctb, ctbEW);

                    TrailerInfo trailerInfo = new TrailerInfo();
                    trailerInfo.setLspId(lspInfo.getId());
                    trailerInfo.setTenantId(lspInfo.getTenantId());
                    trailerInfo.setId(ctb.getTrailerId());
                    trailerInfoService.updateLspInfo(trailerInfo);

                    fleetBindService.deleteFleetBind(ctb.getTrailerId(),
                            TableStatusEnum.STATUS_02.getCode());

                    CarrierTrailerBindLog ctbl = new CarrierTrailerBindLog();
                    ctbl.setCarrierId(carrierId);
                    ctbl.setTenantId(lspInfo.getTenantId());
                    ctbl.setTrailerId(ctb.getTrailerId());
                    ctbl.setGmtCreate(new Date());
                    carrierTrailerBindLogService.insert(ctbl);
                }
                if (dcb != null) {
                    dcb.setTenantId(lspInfo.getTenantId());
                    driverCarrierBindService.update(dcb, driverCarrierBindWrapper);
                    Driver oldDriver = driverService.selectById(dcb.getDriverId());
                    if (oldDriver.getAccountId() == null) {
                        throw new BaseException(-1, "司机" + oldDriver.getName() + "账号不存在！");
                    }

                    List<DriverCheckin> list = driverCheckinService.selectByNowDayNoTenant(dcb.getDriverId());
                    if (!org.apache.commons.collections4.CollectionUtils.isEmpty(list)) {
                        throw new BaseException("绑定的司机存在报班信息,不能转移");
                    }

                    Driver newDriver = new Driver();
                    newDriver.setId(dcb.getDriverId());
                    newDriver.setTenantId(lspInfo.getTenantId());
                    newDriver.setLspId(lspInfo.getId());
                    driverService.updateDriverLspRelation(newDriver);

                    fleetBindService.deleteFleetBind(dcb.getDriverId(), TableStatusEnum.STATUS_03.getCode());

                    List<NameValuePair> headNamePairs = Lists.newArrayList();
                    headNamePairs.add(new BasicNameValuePair("Authorization", authorization));
                    List<NameValuePair> pram = Lists.newArrayList();
                    pram.add(new BasicNameValuePair("DriverId", oldDriver.getId().toString()));
                    String driverWaybill = HttpClientUtil.get(driverWaybillUrl, headNamePairs, pram, socketTimeout);
                    JSONObject driverWayBill = JSONObject.parseObject(driverWaybill);
                    if (!driverWayBill.getBoolean("data")) {
                        throw new BaseException(-1, "司机" + oldDriver.getName() + "还有未完成的运单！");
                    }
                    Map<String, String> prams = new HashMap<>();
                    prams.put("accountId", oldDriver.getAccountId().toString());
                    prams.put("originalTenantId", oldDriver.getTenantId().toString());
                    prams.put("newTenantId", lspInfo.getTenantId().toString());
                    String result = HttpClientUtil.post(uaaUrl + updateTenantOfAccountUrl, headNamePairs, prams, socketTimeout);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    if (jsonObject.getInteger("code") != 0) {
                        LOGGER.error("转移更新司机账号 errer :{}", jsonObject.get("message").toString());
                        throw new BaseException(-1, "司机" + newDriver.getName() + "账号更新异常," + jsonObject.get("message").toString());
                    }
                }
            } else {
                if (ctb != null) {
                    carrierTrailerBindService.deleteById(ctb);
                }
                if (dcb != null) {
                    driverCarrierBindService.delete(driverCarrierBindWrapper);
                }
            }

            // 调整后的信息  推送ERP
            carrierInfoService.carrierToERP(authorization, carrierId);
            //调整后的信息 推送OTM
            if (ctb != null) {
                trailerInfoService.authTrailerToERP(ctb.getTrailerId(), authorization);
            }
            if (dcb != null) {
                driverService.authDriverToERP(authorization, dcb.getDriverId());
            }
            carrierAndTrailerToOtm(carrierId, IntegrationEnum.ISACTIVE.getCode());
            //转移牵引车同时推一遍司机
            if (Objects.nonNull(dcb)) {
                driverService.driverToOtm(dcb.getDriverId());
            }
        });
        return true;
    }


    @Override
    @Transactional
    public boolean changeLspAndRelation(Long[] carrierIds, Long lspId) {
        //只调整车辆所属承运商
//        baseMapper.updateLsp(Arrays.asList(carrierIds),lspId);
//
//        //调整司机所属承运商
//        List<Integer> driverIds = listDriverIdsByCarrier(carrierIds);
//        driverService.onlyChangeLsp(driverIds,lspId);
//
//        //调整牵引车所属承运商
//        List<Integer> trailerIds = listTrailerIdsByCarrier(carrierIds);
//        trailerInfoService.changeLsp(trailerIds,lspId);
        return true;
    }

    //判断证照有效性
    private Integer getValidStatus(CarrierLicense carrierLicense, Boolean isHaveAttach) {
        if (Objects.isNull(isHaveAttach)) {
            // 查找证照的附件信息
            Wrapper<CarrierLicenseAttach> licenseAttachEntity = new EntityWrapper<>();
            licenseAttachEntity.eq("license_id", carrierLicense.getId()).eq("carrier_id", carrierLicense.getCarrierId());
            List<CarrierLicenseAttach> lspLicenseAttachList = carrierLicenseAttachService.selectList(licenseAttachEntity);
            if (!CollectionUtils.isEmpty(lspLicenseAttachList)) {
                isHaveAttach = true;
            }
        }

        // 根据时间
        if (Objects.nonNull(carrierLicense.getGmtReg()) && Objects.nonNull(carrierLicense.getGmtOverdue()) && isHaveAttach &&
                carrierLicense.getGmtOverdue().compareTo(carrierLicense.getGmtReg()) >= 0 && carrierLicense.getGmtOverdue().compareTo(new Date()) >= 0
                && !StringUtils.isEmpty(carrierLicense.getLicenseId())) {
            return LicenseStatusEnum.VALID.getCode();
        } else {
            return LicenseStatusEnum.INVALID.getCode();
        }
    }

    @Override
    @Transactional
    public void submitVehicle(VehicleVO vehicleVO, String authorization) throws BaseException {

        CarrierInfoBO carrierInfoBO = new CarrierInfoBO();
        TrailerInfoBO trailerInfoBO = new TrailerInfoBO();
        String tenantId = AccountUtil.getAccountInfoFromSecurityContext().getTenantId();
        //牵引车
        BeanUtils.copyProperties(vehicleVO.getCarrierInfo(), carrierInfoBO);
        //挂车
        BeanUtils.copyProperties(vehicleVO.getTrailerInfo(), trailerInfoBO);
        //司机的ID
        Long driverId = vehicleVO.getDriverId();
        Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        CarrierInfo carrierInfo = null;
        TrailerInfo trailerInfo = null;
        JwtAccountVO jwtAccount = AccountUtil.getAccountInfoFromSecurityContext();
        try {
            //验证司机
            Driver driver = driverService.selectById(driverId);
            if (Objects.isNull(driver)) {
                throw new BaseException("司机信息不存在");
            }

            String carrierPlate = carrierInfoBO.getPlate();
            String carrierAttachKey = carrierInfoBO.getAttachKey();
            String carrierAttachKey2 = carrierInfoBO.getAttachKeyTwo();
            String trailerPlate = trailerInfoBO.getPlate();
            String trailerAttachKey = trailerInfoBO.getAttachKey();
            String trailerAttachKey2 = trailerInfoBO.getAttachKeyTwo();

            //先判断是否为空
            if (org.apache.commons.lang3.StringUtils.isBlank(carrierAttachKey)) {
                throw new BaseException("牵引车照片1不能为空！");
            }
            if (org.apache.commons.lang3.StringUtils.isBlank(carrierAttachKey2)) {
                throw new BaseException("牵引车照片2不能为空！");
            }
            if (org.apache.commons.lang3.StringUtils.isBlank(trailerAttachKey)) {
                throw new BaseException("挂车照片1不能为空！");
            }
            if (org.apache.commons.lang3.StringUtils.isBlank(trailerAttachKey2)) {
                throw new BaseException("挂车照片2不能为空！");
            }
            if (carrierAttachKey.equals(carrierAttachKey2)) {
                throw new BaseException("牵引车照片不能相同！");
            }
            if (trailerAttachKey.equals(trailerAttachKey2)) {
                throw new BaseException("挂车照片不能相同！");
            }
            if (org.apache.commons.lang3.StringUtils.isBlank(carrierPlate)) {
                throw new BaseException(VehicleException.CARRIER_PLATE_IS_NULL.getCode(), VehicleException.CARRIER_PLATE_IS_NULL.getText());
            }
            if (org.apache.commons.lang3.StringUtils.isBlank(trailerPlate)) {
                throw new BaseException(VehicleException.TRAILER_PLATE_IS_NULL.getCode(), VehicleException.TRAILER_PLATE_IS_NULL.getText());
            }
            if (org.apache.commons.lang3.StringUtils.isBlank(trailerInfoBO.getTrailerType())) {
                throw new BaseException("挂车类型不能为空");
            }
            String substring = trailerPlate.substring(trailerPlate.length() - 1, trailerPlate.length());
            if (!"挂".contains(substring)) {
                throw new BaseException("挂车车牌号不正确:XXX挂");
            }
            char[] trailerPlateChars = trailerPlate.toCharArray();
            for (char trailerPlateChar : trailerPlateChars) {
                if (Character.isLowerCase(trailerPlateChar)) throw new BaseException("挂车车牌号存在小写");
            }
            char[] carrierPlateChars = carrierPlate.toCharArray();
            for (char carrierPlateChar : carrierPlateChars) {
                if (Character.isLowerCase(carrierPlateChar)) throw new BaseException("牵引车车牌号存在小写");
            }
            // 牵引车照片
//            List<CarrierLicenseAttach> carrierPhotographys = carrierInfoBO.getCarrierPhotography();
//            if(null == carrierPhotographys || carrierPhotographys.isEmpty()){
//                throw new BaseException("牵引车照片不能为空！");
//            }
            // 挂车照片
//            List<TrailerLicenseAttach> trailerPhotographys = trailerInfoBO.getTrailerPhotography();
//            if(null == trailerPhotographys || trailerPhotographys.isEmpty()){
//                throw new BaseException("挂车照片不能为空！");
//            }
            //验证司机与牵引车是否可以绑定
            verifyCarrier(driverId, carrierPlate);
            //验证挂车是否可以绑定
            trailerInfoService.verifyTrailerInfoByCarrier(driverId, carrierPlate, trailerPlate);

            //先判断是否牵引车是否在库
            EntityWrapper<CarrierInfo> carrierInfoEntityWrapper = new EntityWrapper<>();
            carrierInfoEntityWrapper.eq("plate", carrierPlate);
            List<CarrierInfo> carrierInfoList = baseMapper.selectCarrierNoTenant(carrierInfoEntityWrapper);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(carrierInfoList)) {
                carrierInfo = carrierInfoList.get(0);
            } else {
                //不在库则新建
                carrierInfo = new CarrierInfo();
                BeanUtils.copyProperties(carrierInfoBO, carrierInfo);
                carrierInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
                carrierInfo.setLspId(driver.getLspId());
                carrierInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
                carrierInfo.setCreateFrom(SourceEnum.WEIXIN.getText());
                carrierInfo.setTenantId(driver.getTenantId());
                carrierInfo.setTenantId(driver.getTenantId());
                this.insert(carrierInfo);
            }

            //判断牵引车和司机是否已经是是绑定关系，如果不是，则进行校验
            DriverCarrierBind driverCarrierBind = driverCarrierBindService.getCarrierBindByCarIdAndDriId(carrierInfo.getId(), driverId);
            if (Objects.isNull(driverCarrierBind)) {
                //新建绑定关系
                driverCarrierBind = new DriverCarrierBind();
                driverCarrierBind.setCarrierId(carrierInfo.getId());
                driverCarrierBind.setDriverId(driverId);
                driverCarrierBind.setGmtCreate(new Date());
                driverCarrierBind.setTenantId(Long.valueOf(tenantId));
                driverCarrierBindService.insert(driverCarrierBind);
                //编写绑定关系的日志
                DriverCarrierBindLog log = new DriverCarrierBindLog();
                log.setCarrierId(carrierInfo.getId());
                log.setDriverId(driverId);
                log.setGmtCreate(new Date());
                log.setTenantId(Long.valueOf(tenantId));
                driverCarrierBindLogService.insert(log);
            }

            //先判断库里是否存在已存在挂车
            EntityWrapper<TrailerInfo> trailerInfoEntityWrapper = new EntityWrapper<>();
            trailerInfoEntityWrapper.eq("plate", trailerPlate);
            List<TrailerInfo> trailerInfoList = trailerInfoService.selectList(trailerInfoEntityWrapper);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(trailerInfoList)) {
                trailerInfo = trailerInfoList.get(0);
                trailerInfo.setTrailerType(trailerInfoBO.getTrailerType());
                if (trailerInfo.getAuthStatus() != 1) {
                    trailerInfoService.update(trailerInfo, trailerInfoEntityWrapper);
                }
            } else {
                //不在库则新建
                trailerInfo = new TrailerInfo();
                BeanUtils.copyProperties(trailerInfoBO, trailerInfo);
                trailerInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
                trailerInfo.setLspId(driver.getLspId());
                trailerInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
                trailerInfo.setCreateFrom(SourceEnum.WEIXIN.getText());
                if (Objects.nonNull(jwtAccount)) {
                    trailerInfo.setCreator(jwtAccount.getAccountId());
                }
                trailerInfo.setTenantId(driver.getTenantId());
                trailerInfoService.insert(trailerInfo);
            }

            //判断牵引车和挂车是否已经是是绑定关系，如果不是，则进行校验
            CarrierTrailerBind carrierTrailerBind = carrierTrailerBindService.getCarrierTrailerBindByTIdAndCId(trailerInfo.getId(), carrierInfo.getId());
            if (Objects.isNull(carrierTrailerBind)) {
                //新建绑定关系
                carrierTrailerBind = new CarrierTrailerBind();
                carrierTrailerBind.setCarrierId(carrierInfo.getId());
                carrierTrailerBind.setTrailerId(trailerInfo.getId());
                carrierTrailerBind.setGmtCreate(new Date());
                carrierTrailerBind.setTenantId(Long.valueOf(tenantId));
                carrierTrailerBindService.insert(carrierTrailerBind);
                //编写绑定关系的日志
                CarrierTrailerBindLog log = new CarrierTrailerBindLog();
                log.setCarrierId(carrierInfo.getId());
                log.setTrailerId(trailerInfo.getId());
                log.setGmtCreate(new Date());
                log.setTenantId(Long.valueOf(tenantId));
                carrierTrailerBindLogService.insert(log);
            }

            // modify by fanguangji 2018-12-06 微信端添加牵引车照片两张
            //是否有牵引车照片
            addCarrierLicenseAttach(carrierInfoBO, carrierInfo, carrierAttachKey, carrierAttachKey2);

            // modify by fanguangji 2018-12-06 微信端添加挂车照片两张
            //是否有挂车照片
            addTrailerLicenseAttach(trailerInfoBO, trailerInfo, trailerAttachKey, trailerAttachKey2);

            //是否有牵引车行驶证信息
            LicenseTypeVo licenseTypeVo = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.VEHICLE_VEHICLE_LICENSE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
            if (Objects.isNull(licenseTypeVo)) {
                throw new BaseException("缺少牵引车证照类型");
            }
            EntityWrapper<CarrierLicense> ew1 = new EntityWrapper<>();
            ew1.eq("license_type_id", licenseTypeVo.getId()).eq("carrier_id", carrierInfo.getId());
            List<CarrierLicense> dls = carrierLicenseService.selectList(ew1);
            CarrierLicense vehicleCarrierLicense = new CarrierLicense();
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(dls)) {
                //不存在则新增
                vehicleCarrierLicense.setLicenseTypeId(licenseTypeVo.getId());
                vehicleCarrierLicense.setCarrierId(carrierInfo.getId());
                carrierLicenseService.insert(vehicleCarrierLicense);
            } else {
                vehicleCarrierLicense = dls.get(0);
            }

            //判断是否上传 行驶证附件信息
            if (org.apache.commons.lang3.StringUtils.isNotBlank(carrierInfoBO.getVehicleLicenseKey())) {
                EntityWrapper<CarrierLicenseAttach> carrierLicenseAttachEntityWrapper = new EntityWrapper<>();
                carrierLicenseAttachEntityWrapper.eq("license_id", vehicleCarrierLicense.getId()).eq("carrier_id", carrierInfo.getId());
                List<CarrierLicenseAttach> carrierLicenseAttaches = carrierLicenseAttachService.selectList(carrierLicenseAttachEntityWrapper);
                if (org.apache.commons.collections4.CollectionUtils.isEmpty(carrierLicenseAttaches)) {
                    CarrierLicenseAttach carrierLicenseAttach = new CarrierLicenseAttach();
                    carrierLicenseAttach.setLicenseId(vehicleCarrierLicense.getId());
                    carrierLicenseAttach.setAttachType(AttachtypeEnum.POSITIVE.getCode());
                    carrierLicenseAttach.setAttachKey(carrierInfoBO.getVehicleLicenseKey());
                    carrierLicenseAttach.setAttachName(carrierInfoBO.getVehicleLicenseAttachName());
                    carrierLicenseAttach.setCarrierId(carrierInfo.getId());
                    carrierLicenseAttachService.insert(carrierLicenseAttach);
                    carrierLicenseService.updateLicense(carrierInfoBO.getVehicleLicenseKey(), vehicleCarrierLicense.getId(), authorization);
                } else {
                    CarrierLicenseAttach oldCarrierLicenseAttach = carrierLicenseAttaches.get(0);
                    if (org.apache.commons.lang3.StringUtils.isBlank(oldCarrierLicenseAttach.getAttachKey()) || !carrierInfoBO.getVehicleLicenseKey().equals(oldCarrierLicenseAttach.getAttachKey())) {
//                        if(StringUtils.isNotEmpty(oldCarrierLicenseAttach.getAttachKey())){
//                            uploadService.deleteFile(oldCarrierLicenseAttach.getAttachKey());
//                        }
                        oldCarrierLicenseAttach.setAttachKey(carrierInfoBO.getVehicleLicenseKey());
                        oldCarrierLicenseAttach.setAttachName(carrierInfoBO.getVehicleLicenseAttachName());
                        carrierLicenseAttachService.updateById(oldCarrierLicenseAttach);
                        //牵引车行驶证自动识别
                        carrierLicenseService.updateLicense(carrierInfoBO.getVehicleLicenseKey(), vehicleCarrierLicense.getId(), authorization);
                    }

                }
            }


            //是否有牵引车运营许可证信息
            LicenseTypeVo licenseTypeBO2 = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.VEHICLE_OPERATING_LICENSE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
            if (Objects.isNull(licenseTypeBO2)) {
                throw new BaseException("缺少证照类型");
            }
            EntityWrapper<CarrierLicense> ew2 = new EntityWrapper<>();
            ew2.eq("license_type_id", licenseTypeBO2.getId()).eq("carrier_id", carrierInfo.getId());
            List<CarrierLicense> operatingCarrierLicenses = carrierLicenseService.selectList(ew2);
            CarrierLicense operatingCarrierLicense = new CarrierLicense();
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(operatingCarrierLicenses)) {
                operatingCarrierLicense.setLicenseTypeId(licenseTypeBO2.getId());
                operatingCarrierLicense.setCarrierId(carrierInfo.getId());
                carrierLicenseService.insert(operatingCarrierLicense);
            } else {
                operatingCarrierLicense = operatingCarrierLicenses.get(0);
            }

            //判断是否上传 运营许可证附件信息
            if (org.apache.commons.lang3.StringUtils.isNotBlank(carrierInfoBO.getOperatingLicenseKey())) {
                EntityWrapper<CarrierLicenseAttach> carrierLicenseAttachEntityWrapper = new EntityWrapper<>();
                carrierLicenseAttachEntityWrapper.eq("license_id", operatingCarrierLicense.getId()).eq("carrier_id", carrierInfo.getId());
                List<CarrierLicenseAttach> carrierLicenseAttaches = carrierLicenseAttachService.selectList(carrierLicenseAttachEntityWrapper);
                if (org.apache.commons.collections4.CollectionUtils.isEmpty(carrierLicenseAttaches)) {
                    CarrierLicenseAttach carrierLicenseAttach = new CarrierLicenseAttach();
                    carrierLicenseAttach.setLicenseId(operatingCarrierLicense.getId());
                    carrierLicenseAttach.setAttachType(AttachtypeEnum.POSITIVE.getCode());
                    carrierLicenseAttach.setAttachKey(carrierInfoBO.getOperatingLicenseKey());
                    carrierLicenseAttach.setAttachName(carrierInfoBO.getOperatingLicenseAttachName());
                    carrierLicenseAttach.setCarrierId(carrierInfo.getId());
                    carrierLicenseAttachService.insert(carrierLicenseAttach);
                } else {
                    CarrierLicenseAttach oldCarrierLicenseAttach = carrierLicenseAttaches.get(0);
                    if (org.apache.commons.lang3.StringUtils.isBlank(oldCarrierLicenseAttach.getAttachKey()) || !carrierInfoBO.getOperatingLicenseKey().equals(oldCarrierLicenseAttach.getAttachKey())) {
//                        if(StringUtils.isNotEmpty(oldCarrierLicenseAttach.getAttachKey())){
//                            uploadService.deleteFile(oldCarrierLicenseAttach.getAttachKey());
//                        }
                        oldCarrierLicenseAttach.setAttachKey(carrierInfoBO.getOperatingLicenseKey());
                        oldCarrierLicenseAttach.setAttachName(carrierInfoBO.getOperatingLicenseAttachName());
                        carrierLicenseAttachService.updateById(oldCarrierLicenseAttach);
                    }
                }
            }


            //获取挂车行驶证信息
            EntityWrapper<TrailerLicense> ew3 = new EntityWrapper<>();
            ew3.eq("license_type_id", licenseTypeVo.getId()).eq("trailer_id", trailerInfo.getId());
            List<TrailerLicense> trailerLicenses = trailerLicenseService.selectList(ew3);
            TrailerLicense vehicleTrailerLicense = new TrailerLicense();
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(trailerLicenses)) {
                vehicleTrailerLicense.setLicenseTypeId(licenseTypeVo.getId());
                vehicleTrailerLicense.setTrailerId(trailerInfo.getId());
                trailerLicenseService.insert(vehicleTrailerLicense);
            } else {
                vehicleTrailerLicense = trailerLicenses.get(0);
            }

            //是否上传了挂车行驶证信息
            if (org.apache.commons.lang3.StringUtils.isNotBlank(trailerInfoBO.getVehicleLicenseKey())) {
                EntityWrapper<TrailerLicenseAttach> trailerLicenseAttachEntityWrapper = new EntityWrapper<>();
                trailerLicenseAttachEntityWrapper.eq("license_id", vehicleTrailerLicense.getId()).eq("trailer_id", trailerInfo.getId());
                List<TrailerLicenseAttach> trailerLicenseAttaches = trailerLicenseAttachService.selectList(trailerLicenseAttachEntityWrapper);
                if (org.apache.commons.collections4.CollectionUtils.isEmpty(trailerLicenseAttaches)) {
                    TrailerLicenseAttach trailerLicenseAttach = new TrailerLicenseAttach();
                    trailerLicenseAttach.setLicenseId(vehicleTrailerLicense.getId());
                    trailerLicenseAttach.setAttachType(AttachtypeEnum.POSITIVE.getCode());
                    trailerLicenseAttach.setAttachKey(trailerInfoBO.getVehicleLicenseKey());
                    trailerLicenseAttach.setAttachName(trailerInfoBO.getVehicleLicenseAttachName());
                    trailerLicenseAttach.setTrailerId(trailerInfo.getId());
                    trailerLicenseAttachService.insert(trailerLicenseAttach);
                    trailerLicenseService.updateLicense(trailerInfoBO.getVehicleLicenseKey(), vehicleTrailerLicense.getId(), authorization);
                } else {
                    TrailerLicenseAttach oldTrailerLicenseAttach = trailerLicenseAttaches.get(0);
                    if (org.apache.commons.lang3.StringUtils.isBlank(oldTrailerLicenseAttach.getAttachKey()) || !trailerInfoBO.getVehicleLicenseKey().equals(oldTrailerLicenseAttach.getAttachKey())) {
//                        if(StringUtils.isNotEmpty(oldTrailerLicenseAttach.getAttachKey())){
//                            uploadService.deleteFile(oldTrailerLicenseAttach.getAttachKey());
//                        }
                        oldTrailerLicenseAttach.setAttachKey(trailerInfoBO.getVehicleLicenseKey());
                        oldTrailerLicenseAttach.setAttachName(trailerInfoBO.getVehicleLicenseAttachName());
                        trailerLicenseAttachService.updateById(oldTrailerLicenseAttach);
                        trailerLicenseService.updateLicense(trailerInfoBO.getVehicleLicenseKey(), vehicleTrailerLicense.getId(), authorization);
                    }
                }

            }


            //是否有挂车运营许可证信息
            EntityWrapper<TrailerLicense> ew4 = new EntityWrapper<>();
            ew4.eq("license_type_id", licenseTypeBO2.getId()).eq("trailer_id", trailerInfo.getId());
            List<TrailerLicense> operatingTrailerLicenses = trailerLicenseService.selectList(ew4);
            TrailerLicense operatingTrailerLicense = new TrailerLicense();
            if (org.apache.commons.collections4.CollectionUtils.isEmpty(operatingTrailerLicenses)) {
                operatingTrailerLicense.setLicenseTypeId(licenseTypeBO2.getId());
                operatingTrailerLicense.setTrailerId(trailerInfo.getId());
                trailerLicenseService.insert(operatingTrailerLicense);
            } else {
                operatingTrailerLicense = operatingTrailerLicenses.get(0);
            }


            //判断是否上传 运营许可证附件信息
            if (org.apache.commons.lang3.StringUtils.isNotBlank(trailerInfoBO.getOperatingLicenseKey())) {
                EntityWrapper<TrailerLicenseAttach> trailerLicenseAttachEntityWrapper = new EntityWrapper<>();
                trailerLicenseAttachEntityWrapper.eq("license_id", operatingTrailerLicense.getId()).eq("trailer_id", trailerInfo.getId());
                List<TrailerLicenseAttach> trailerLicenseAttaches = trailerLicenseAttachService.selectList(trailerLicenseAttachEntityWrapper);
                if (org.apache.commons.collections4.CollectionUtils.isEmpty(trailerLicenseAttaches)) {
                    TrailerLicenseAttach trailerLicenseAttach = new TrailerLicenseAttach();
                    trailerLicenseAttach.setLicenseId(operatingTrailerLicense.getId());
                    trailerLicenseAttach.setAttachType(AttachtypeEnum.POSITIVE.getCode());
                    trailerLicenseAttach.setAttachKey(trailerInfoBO.getOperatingLicenseKey());
                    trailerLicenseAttach.setAttachName(trailerInfoBO.getOperatingLicenseAttachName());
                    trailerLicenseAttach.setTrailerId(trailerInfo.getId());
                    trailerLicenseAttachService.insert(trailerLicenseAttach);
                } else {
                    TrailerLicenseAttach oldTrailerLicenseAttach = trailerLicenseAttaches.get(0);
                    if (org.apache.commons.lang3.StringUtils.isBlank(oldTrailerLicenseAttach.getAttachKey()) || !trailerInfoBO.getOperatingLicenseKey().equals(oldTrailerLicenseAttach.getAttachKey())) {
//                        if(StringUtils.isNotEmpty(oldTrailerLicenseAttach.getAttachKey())){
//                            uploadService.deleteFile(oldTrailerLicenseAttach.getAttachKey());
//                        }
                        oldTrailerLicenseAttach.setAttachKey(trailerInfoBO.getOperatingLicenseKey());
                        oldTrailerLicenseAttach.setAttachName(trailerInfoBO.getOperatingLicenseAttachName());
                        trailerLicenseAttachService.updateById(oldTrailerLicenseAttach);
                    }
                }
            }
        } catch (Exception ex) {
            throw new BaseException(ex.getMessage());
        }
    }

    private void addTrailerLicenseAttach(TrailerInfoBO trailerInfoBO, TrailerInfo trailerInfo, String trailerAttachKey, String trailerAttachKey2) {
        LicenseTypeVo licenseTypeTrailer = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.TRAILER_LICENCE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
        if (Objects.isNull(licenseTypeTrailer)) {
            throw new BaseException("缺少挂车照片类型");
        }
        EntityWrapper<TrailerLicense> ewTrailer = new EntityWrapper<>();
        ewTrailer.eq("license_type_id", licenseTypeTrailer.getId());
        ewTrailer.eq("trailer_id", trailerInfo.getId());
        List<TrailerLicense> trailerLicenseList = trailerLicenseService.selectList(ewTrailer);
        TrailerLicense trailerLicense = new TrailerLicense();
        if (CollectionUtils.isEmpty(trailerLicenseList)) {
            //不存在则新增
            trailerLicense.setLicenseTypeId(licenseTypeTrailer.getId());
            trailerLicense.setTrailerId(trailerInfo.getId());
            trailerLicenseService.insert(trailerLicense);
        } else {
            trailerLicense = trailerLicenseList.get(0);
        }
        // 先删除在添加
        EntityWrapper<TrailerLicenseAttach> ewTrailerAttach = new EntityWrapper<>();
        ewTrailerAttach.eq("trailer_id", trailerInfo.getId());
        ewTrailerAttach.eq("license_id", trailerLicense.getId());
        ewTrailerAttach.eq("attach_type", TableStatusEnum.STATUS_05.getCode());
        trailerLicenseAttachService.delete(ewTrailerAttach);
        // 添加挂车照片1
        TrailerLicenseAttach trailerLicenseAttach1 = new TrailerLicenseAttach();
        trailerLicenseAttach1.setLicenseId(trailerLicense.getId());
        trailerLicenseAttach1.setAttachType(TableStatusEnum.STATUS_05.getCode());
        trailerLicenseAttach1.setAttachKey(trailerAttachKey);
        trailerLicenseAttach1.setAttachName(trailerInfoBO.getAttachName());
        trailerLicenseAttach1.setTrailerId(trailerInfo.getId());
        trailerLicenseAttachService.insert(trailerLicenseAttach1);
        // 添加挂车照片2
        TrailerLicenseAttach trailerLicenseAttach2 = new TrailerLicenseAttach();
        trailerLicenseAttach2.setLicenseId(trailerLicense.getId());
        trailerLicenseAttach2.setAttachType(TableStatusEnum.STATUS_05.getCode());
        trailerLicenseAttach2.setAttachKey(trailerAttachKey2);
        trailerLicenseAttach2.setAttachName(trailerInfoBO.getAttachNameTwo());
        trailerLicenseAttach2.setTrailerId(trailerInfo.getId());
        trailerLicenseAttachService.insert(trailerLicenseAttach2);
    }

    private void addCarrierLicenseAttach(CarrierInfoBO carrierInfoBO, CarrierInfo carrierInfo, String carrierAttachKey, String carrierAttachKey2) {
        LicenseTypeVo licenseTypeCarrier = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.CARRIER_LICENCE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
        if (Objects.isNull(licenseTypeCarrier)) {
            throw new BaseException("缺少牵引车照片类型");
        }
        EntityWrapper<CarrierLicense> ewCarrier = new EntityWrapper<>();
        ewCarrier.eq("license_type_id", licenseTypeCarrier.getId());
        ewCarrier.eq("carrier_id", carrierInfo.getId());
        List<CarrierLicense> carrierLicenses = carrierLicenseService.selectList(ewCarrier);
        CarrierLicense carrierLicense = new CarrierLicense();
        if (CollectionUtils.isEmpty(carrierLicenses)) {
            //不存在则新增
            carrierLicense.setLicenseTypeId(licenseTypeCarrier.getId());
            carrierLicense.setCarrierId(carrierInfo.getId());
            carrierLicenseService.insert(carrierLicense);
        } else {
            carrierLicense = carrierLicenses.get(0);
        }
        // 先删除在添加
        EntityWrapper<CarrierLicenseAttach> ewAttach = new EntityWrapper<>();
        ewAttach.eq("carrier_id", carrierInfo.getId());
        ewAttach.eq("license_id", carrierLicense.getId());
        ewAttach.eq("attach_type", TableStatusEnum.STATUS_04.getCode());
        carrierLicenseAttachService.delete(ewAttach);
        // 添加牵引车照片1
        CarrierLicenseAttach carrierLicenseAttach1 = new CarrierLicenseAttach();
        carrierLicenseAttach1.setLicenseId(carrierLicense.getId());
        carrierLicenseAttach1.setAttachType(TableStatusEnum.STATUS_04.getCode());
        carrierLicenseAttach1.setAttachKey(carrierAttachKey);
        carrierLicenseAttach1.setAttachName(carrierInfoBO.getAttachName());
        carrierLicenseAttach1.setCarrierId(carrierInfo.getId());
        carrierLicenseAttachService.insert(carrierLicenseAttach1);
        // 添加牵引车照片2
        CarrierLicenseAttach carrierLicenseAttach2 = new CarrierLicenseAttach();
        carrierLicenseAttach2.setLicenseId(carrierLicense.getId());
        carrierLicenseAttach2.setAttachType(TableStatusEnum.STATUS_04.getCode());
        carrierLicenseAttach2.setAttachKey(carrierAttachKey2);
        carrierLicenseAttach2.setAttachName(carrierInfoBO.getAttachNameTwo());
        carrierLicenseAttach2.setCarrierId(carrierInfo.getId());
        carrierLicenseAttachService.insert(carrierLicenseAttach2);
    }

    @Override
    public void submitVehicleAttach(AttachVO attachVO) {
        Long LicenseType = null;
        String attachType = null;
        if (attachVO.getKeyTypeName().equals("carrierOperating")) {
            LicenseType = new Long(LicenseTypeEnum.VEHICLE_OPERATING_LICENSE.getCode().substring(3, 5));
            attachType = AttachtypeEnum.POSITIVE.getCode();
        } else if (attachVO.getKeyTypeName().equals("carrierVehicle")) {
            LicenseType = new Long(LicenseTypeEnum.VEHICLE_VEHICLE_LICENSE.getCode().substring(3, 5));
            attachType = AttachtypeEnum.POSITIVE.getCode();
        } else if (attachVO.getKeyTypeName().equals("trailerOperating")) {
            LicenseType = new Long(LicenseTypeEnum.VEHICLE_OPERATING_LICENSE.getCode().substring(3, 5));
            attachType = AttachtypeEnum.POSITIVE.getCode();
        } else if (attachVO.getKeyTypeName().equals("trailerVehicle")) {
            LicenseType = new Long(LicenseTypeEnum.VEHICLE_VEHICLE_LICENSE.getCode().substring(3, 5));
            attachType = AttachtypeEnum.POSITIVE.getCode();
        } else {
            throw new BaseException("未找到匹配类型");
        }
        if (attachVO.getKeyTypeName().indexOf("carrier") > 0) {
            ModifyCarrierInfoBO modifyCarrierInfoBO = new ModifyCarrierInfoBO();
            modifyCarrierInfoBO.setId(attachVO.getDriverId());
            List<ModifyCarrierLicenseBO> modifyCarrierLicenseBOS = new ArrayList<>();
            ModifyCarrierLicenseBO modifyCarrierLicenseBO = new ModifyCarrierLicenseBO();
            modifyCarrierLicenseBO.setLicenseTypeId(LicenseType);
            //附件信息
            List<CarrierLicenseAttach> carrierLicenseAttaches = new ArrayList<>();
            CarrierLicenseAttach carrierLicenseAttach = new CarrierLicenseAttach();
            carrierLicenseAttach.setAttachKey(attachVO.getKey());
            carrierLicenseAttach.setAttachName(attachVO.getAttachName());
            carrierLicenseAttach.setAttachType(attachType);
            carrierLicenseAttaches.add(carrierLicenseAttach);
            modifyCarrierLicenseBO.setCarrierLicenseAttachList(carrierLicenseAttaches);
            modifyCarrierLicenseBOS.add(modifyCarrierLicenseBO);
            modifyCarrierInfoBO.setModifyCarrierLicenseBOList(modifyCarrierLicenseBOS);
            this.updateLicense(modifyCarrierInfoBO);
        } else {
            ModifyTrailerInfoBO modifyTrailerInfoBO = new ModifyTrailerInfoBO();
            modifyTrailerInfoBO.setId(attachVO.getDriverId());
            List<ModifyTrailerLicenseBO> modifyTrailerLicenseBOS = new ArrayList<>();
            ModifyTrailerLicenseBO modifyTrailerLicenseBO = new ModifyTrailerLicenseBO();
            modifyTrailerLicenseBO.setLicenseTypeId(LicenseType);
            //附件信息
            List<TrailerLicenseAttach> trailerLicenseAttaches = new ArrayList<>();
            TrailerLicenseAttach trailerLicenseAttach = new TrailerLicenseAttach();
            trailerLicenseAttach.setAttachKey(attachVO.getKey());
            trailerLicenseAttach.setAttachName(attachVO.getAttachName());
            trailerLicenseAttach.setAttachType(attachType);
            trailerLicenseAttaches.add(trailerLicenseAttach);
            modifyTrailerLicenseBO.setTrailerLicenseAttachList(trailerLicenseAttaches);
            modifyTrailerLicenseBOS.add(modifyTrailerLicenseBO);
            modifyTrailerInfoBO.setModifyTrailerLicenseBOList(modifyTrailerLicenseBOS);
            trailerInfoService.updateLicense(modifyTrailerInfoBO);
        }
    }

    @Override
    public VehicleBO getVehicleByDriverId(Long list) {
        VehicleBO vehicleBO = new VehicleBO();
        //加入司机
        vehicleBO.setDriverId(list);

        //获取牵引车
        CarrierInfoBO carrierInfoBO = selectByDriverId(list);
        TrailerInfoBO trailerInfoBO = null;

        String width = "160";
        String heigth = "105";

        if (Objects.nonNull(carrierInfoBO)) {
            //获取牵引车 行驶证信息
            LicenseTypeVo licenseTypeBO = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.VEHICLE_VEHICLE_LICENSE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
            if (Objects.isNull(licenseTypeBO)) {
                throw new BaseException("缺少证照类型");
            }
            EntityWrapper<CarrierLicense> ew1 = new EntityWrapper<>();
            ew1.eq("license_type_id", licenseTypeBO.getId()).eq("carrier_id", carrierInfoBO.getId());
            List<CarrierLicense> dls = carrierLicenseService.selectList(ew1);
            if (!org.apache.commons.collections4.CollectionUtils.isEmpty(dls)) {
                CarrierLicense carrierLicense = dls.get(0);
                CarrierLicenseBO vehicleLicenseBO = new CarrierLicenseBO();
                BeanUtils.copyProperties(carrierLicense, vehicleLicenseBO);
                if (Objects.nonNull(vehicleLicenseBO.getId())) {
                    EntityWrapper<CarrierLicenseAttach> carrierLicenseAttachEntityWrapper = new EntityWrapper<>();
                    carrierLicenseAttachEntityWrapper.eq("license_id", vehicleLicenseBO.getId()).eq("carrier_id", carrierInfoBO.getId());
                    List<CarrierLicenseAttach> carrierLicenseAttaches = carrierLicenseAttachService.selectList(carrierLicenseAttachEntityWrapper);
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(carrierLicenseAttaches)) {
                        CarrierLicenseAttach carrierLicenseAttach = carrierLicenseAttaches.get(0);
                        carrierInfoBO.setVehicleLicenseKey(carrierLicenseAttach.getAttachKey());
                        carrierInfoBO.setVehicleLicenseAttachName(carrierLicenseAttach.getAttachName());
                        carrierInfoBO.setVehicleLicensePath(uploadService.getStrUrl(carrierLicenseAttach.getAttachKey(), width, heigth));
                    }
                }
            }

            //获取牵引车 运营许可证信息
            LicenseTypeVo licenseTypeBO1 = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.VEHICLE_OPERATING_LICENSE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
            if (Objects.isNull(licenseTypeBO1)) {
                throw new BaseException("缺少证照类型");
            }
            EntityWrapper<CarrierLicense> ew2 = new EntityWrapper<>();
            ew2.eq("license_type_id", licenseTypeBO1.getId()).eq("carrier_id", carrierInfoBO.getId());
            List<CarrierLicense> cls = carrierLicenseService.selectList(ew2);
            if (!org.apache.commons.collections4.CollectionUtils.isEmpty(cls)) {
                CarrierLicense carrierLicense = cls.get(0);
                CarrierLicenseBO operatingLicenseBO = new CarrierLicenseBO();
                BeanUtils.copyProperties(carrierLicense, operatingLicenseBO);
                if (Objects.nonNull(operatingLicenseBO.getId())) {
                    EntityWrapper<CarrierLicenseAttach> carrierLicenseAttachEntityWrapper = new EntityWrapper<>();
                    carrierLicenseAttachEntityWrapper.eq("license_id", operatingLicenseBO.getId()).eq("carrier_id", carrierInfoBO.getId());
                    List<CarrierLicenseAttach> carrierLicenseAttaches = carrierLicenseAttachService.selectList(carrierLicenseAttachEntityWrapper);
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(carrierLicenseAttaches)) {
                        CarrierLicenseAttach carrierLicenseAttach = carrierLicenseAttaches.get(0);
                        carrierInfoBO.setOperatingLicenseKey(carrierLicenseAttach.getAttachKey());
                        carrierInfoBO.setOperatingLicenseAttachName(carrierLicenseAttach.getAttachName());
                        carrierInfoBO.setOperatingLicensePath(uploadService.getStrUrl(carrierLicenseAttach.getAttachKey(), width, heigth));
                    }
                }

            }

            //获取牵引车照片
            LicenseTypeVo licenseTypeBO2 = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.CARRIER_LICENCE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
            if (Objects.isNull(licenseTypeBO2)) {
                throw new BaseException("缺少证照类型");
            }
            EntityWrapper<CarrierLicense> ewCarrierLicense = new EntityWrapper<>();
            ewCarrierLicense.eq("license_type_id", licenseTypeBO2.getId()).eq("carrier_id", carrierInfoBO.getId());
            List<CarrierLicense> clList = carrierLicenseService.selectList(ewCarrierLicense);
            if (!org.apache.commons.collections4.CollectionUtils.isEmpty(clList)) {
                CarrierLicense carrierLicense = clList.get(0);
                CarrierLicenseBO operatingLicenseBO = new CarrierLicenseBO();
                BeanUtils.copyProperties(carrierLicense, operatingLicenseBO);
                if (Objects.nonNull(operatingLicenseBO.getId())) {
                    EntityWrapper<CarrierLicenseAttach> carrierLicenseAttachEW = new EntityWrapper<>();
                    carrierLicenseAttachEW.eq("license_id", operatingLicenseBO.getId());
                    carrierLicenseAttachEW.eq("carrier_id", carrierInfoBO.getId());
                    carrierLicenseAttachEW.eq("attach_type", TableStatusEnum.STATUS_04.getCode());
                    List<CarrierLicenseAttach> carrierLicenseAttaches = carrierLicenseAttachService.selectList(carrierLicenseAttachEW);
                    if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(carrierLicenseAttaches)) {
                        carrierInfoBO.setAttachKey(carrierLicenseAttaches.get(0).getAttachKey());
                        carrierInfoBO.setAttachName(carrierLicenseAttaches.get(0).getAttachName());
                        carrierInfoBO.setAttachPath(uploadService.getStrUrl(carrierLicenseAttaches.get(0).getAttachKey(), width, heigth));
                        if (carrierLicenseAttaches.size() >= 2) {
                            carrierInfoBO.setAttachKeyTwo(carrierLicenseAttaches.get(1).getAttachKey());
                            carrierInfoBO.setAttachNameTwo(carrierLicenseAttaches.get(1).getAttachName());
                            carrierInfoBO.setAttachPathTwo(uploadService.getStrUrl(carrierLicenseAttaches.get(1).getAttachKey(), width, heigth));
                        }
                    }
                }

            }
            //牵引车类型
            if (Objects.nonNull(carrierInfoBO.getTractorType())) {
                if (TractorTypeEnum.TRACTORVEHICLE.getCode().toString().equals(carrierInfoBO.getTractorType()))
                    carrierInfoBO.setTractorTypeName(TractorTypeEnum.TRACTORVEHICLE.getText());
                if (TractorTypeEnum.RECOVERYVEHICLE.getCode().toString().equals(carrierInfoBO.getTractorType()))
                    carrierInfoBO.setTractorTypeName(TractorTypeEnum.RECOVERYVEHICLE.getText());
            }
            vehicleBO.setCarrierInfo(carrierInfoBO);

            //获取绑定的挂的车
            trailerInfoBO = trailerInfoService.selectByCarrierInfoId(carrierInfoBO.getId());
            if (Objects.nonNull(trailerInfoBO)) {
                //获取 挂车行驶证信息
                EntityWrapper<TrailerLicense> ew3 = new EntityWrapper<>();
                ew3.eq("license_type_id", licenseTypeBO.getId()).eq("trailer_id", trailerInfoBO.getId());
                List<TrailerLicense> tls = trailerLicenseService.selectList(ew3);
                if (!org.apache.commons.collections4.CollectionUtils.isEmpty(tls)) {
                    TrailerLicense trailerLicense = tls.get(0);
                    TrailerLicenseBO vehicleTrailerLicenseBO = new TrailerLicenseBO();
                    BeanUtils.copyProperties(trailerLicense, vehicleTrailerLicenseBO);
                    if (Objects.nonNull(vehicleTrailerLicenseBO.getId())) {
                        EntityWrapper<TrailerLicenseAttach> trailerLicenseAttachEntityWrapper = new EntityWrapper<>();
                        trailerLicenseAttachEntityWrapper.eq("license_id", vehicleTrailerLicenseBO.getId()).eq("trailer_id", trailerInfoBO.getId());
                        List<TrailerLicenseAttach> trailerLicenseAttaches = trailerLicenseAttachService.selectList(trailerLicenseAttachEntityWrapper);
                        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(trailerLicenseAttaches)) {
                            TrailerLicenseAttach trailerLicenseAttach = trailerLicenseAttaches.get(0);
                            trailerInfoBO.setVehicleLicenseKey(trailerLicenseAttach.getAttachKey());
                            trailerInfoBO.setVehicleLicenseAttachName(trailerLicenseAttach.getAttachName());
                            trailerInfoBO.setVehicleLicensePath(uploadService.getStrUrl(trailerLicenseAttach.getAttachKey(), width, heigth));
                        }
                    }
                }

                //获取挂车 运营许可证信息
                EntityWrapper<TrailerLicense> ew4 = new EntityWrapper<>();
                ew4.eq("license_type_id", licenseTypeBO1.getId()).eq("trailer_id", trailerInfoBO.getId());
                List<TrailerLicense> tls2 = trailerLicenseService.selectList(ew4);
                if (!org.apache.commons.collections4.CollectionUtils.isEmpty(tls2)) {
                    TrailerLicense trailerLicense = tls2.get(0);
                    TrailerLicenseBO operatingTrailerLicenseBO = new TrailerLicenseBO();
                    BeanUtils.copyProperties(trailerLicense, operatingTrailerLicenseBO);
                    if (Objects.nonNull(operatingTrailerLicenseBO.getId())) {
                        EntityWrapper<TrailerLicenseAttach> trailerLicenseAttachEntityWrapper = new EntityWrapper<>();
                        trailerLicenseAttachEntityWrapper.eq("license_id", operatingTrailerLicenseBO.getId()).eq("trailer_id", trailerInfoBO.getId());
                        List<TrailerLicenseAttach> trailerLicenseAttaches = trailerLicenseAttachService.selectList(trailerLicenseAttachEntityWrapper);
                        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(trailerLicenseAttaches)) {
                            TrailerLicenseAttach trailerLicenseAttach = trailerLicenseAttaches.get(0);
                            trailerInfoBO.setOperatingLicenseKey(trailerLicenseAttach.getAttachKey());
                            trailerInfoBO.setOperatingLicenseAttachName(trailerLicenseAttach.getAttachName());
                            trailerInfoBO.setOperatingLicensePath(uploadService.getStrUrl(trailerLicenseAttach.getAttachKey(), width, heigth));
                        }
                    }
                }

                //获取挂车照片
                LicenseTypeVo licenseTypeBOTrailer = mdmUtil.getLicenseTypeByCode(LicenseTypeEnum.TRAILER_LICENCE.getCode(), SubjectTypeEnum.VEHICLE.getCode());
                if (Objects.isNull(licenseTypeBOTrailer)) {
                    throw new BaseException("缺少证照类型");
                }
                //获取挂车照片信息
                EntityWrapper<TrailerLicense> ewTrailerLicense = new EntityWrapper<>();
                ewTrailerLicense.eq("license_type_id", licenseTypeBOTrailer.getId());
                ewTrailerLicense.eq("trailer_id", trailerInfoBO.getId());
                List<TrailerLicense> tlList = trailerLicenseService.selectList(ewTrailerLicense);
                if (!org.apache.commons.collections4.CollectionUtils.isEmpty(tlList)) {
                    TrailerLicense trailerLicense = tlList.get(0);
                    TrailerLicenseBO operatingTrailerLicenseBO = new TrailerLicenseBO();
                    BeanUtils.copyProperties(trailerLicense, operatingTrailerLicenseBO);
                    if (Objects.nonNull(operatingTrailerLicenseBO.getId())) {
                        EntityWrapper<TrailerLicenseAttach> trailerAttachEW = new EntityWrapper<>();
                        trailerAttachEW.eq("license_id", operatingTrailerLicenseBO.getId());
                        trailerAttachEW.eq("trailer_id", trailerInfoBO.getId());
                        trailerAttachEW.eq("attach_type", TableStatusEnum.STATUS_05.getCode());
                        List<TrailerLicenseAttach> trailerLicenseAttaches = trailerLicenseAttachService.selectList(trailerAttachEW);
                        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(trailerLicenseAttaches)) {
                            TrailerLicenseAttach trailerLicenseAttach = trailerLicenseAttaches.get(0);
                            trailerInfoBO.setAttachKey(trailerLicenseAttach.getAttachKey());
                            trailerInfoBO.setAttachName(trailerLicenseAttach.getAttachName());
                            trailerInfoBO.setAttachPath(uploadService.getStrUrl(trailerLicenseAttach.getAttachKey(), width, heigth));
                            if (trailerLicenseAttaches.size() >= 2) {
                                trailerInfoBO.setAttachKeyTwo(trailerLicenseAttaches.get(1).getAttachKey());
                                trailerInfoBO.setAttachNameTwo(trailerLicenseAttaches.get(1).getAttachName());
                                trailerInfoBO.setAttachPathTwo(uploadService.getStrUrl(trailerLicenseAttaches.get(1).getAttachKey(), width, heigth));
                            }
                        }
                    }
                }
                //绑定挂车类型
                if (Objects.nonNull(trailerInfoBO.getTrailerType())) {
                    List<TransportationTypeVO> allServiceType = mdmUtil.getAllFleetTransportType();
                    String serviceTypeName = trailerInfoBO.getTrailerType();
                    for (TransportationTypeVO transportationTypeVO :
                            allServiceType) {
                        serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
                    }
                    trailerInfoBO.setTrailerTypeName(serviceTypeName);
                }
                vehicleBO.setTrailerInfo(trailerInfoBO);
            } else {
                trailerInfoBO = new TrailerInfoBO();
                vehicleBO.setTrailerInfo(trailerInfoBO);
            }
        } else {
            carrierInfoBO = new CarrierInfoBO();
            vehicleBO.setCarrierInfo(carrierInfoBO);
            trailerInfoBO = new TrailerInfoBO();
            vehicleBO.setTrailerInfo(trailerInfoBO);
        }
        return vehicleBO;
    }

    @Override
    public VehicleBO unbindVehicle(Long list, String plate) throws BaseException {
        Driver driver = driverService.selectById(list);
        if (Objects.isNull(driver)) {
            throw new BaseException("司机信息不存在");
        }

        CarrierInfo carrierInfo = new CarrierInfo();
        carrierInfo.setPlate(plate);
        carrierInfo = baseMapper.selectOne(carrierInfo);

        EntityWrapper<DriverCarrierBind> ew = new EntityWrapper<>();
        ew.eq("driver_id", list).eq("carrier_id", carrierInfo.getId());
        List<DriverCarrierBind> lists = driverCarrierBindService.selectList(ew);
        if (org.apache.commons.collections4.CollectionUtils.isEmpty(lists)) {
            throw new BaseException("没有与该牵引车进行绑定");
        }
        Boolean bln = driverCarrierBindService.delete(ew);
        VehicleBO vehicleBO = new VehicleBO();
        CarrierInfoBO carrierInfoBO = new CarrierInfoBO();
        TrailerInfoBO trailerInfoBO = new TrailerInfoBO();
        vehicleBO.setCarrierInfo(carrierInfoBO);
        vehicleBO.setTrailerInfo(trailerInfoBO);
        vehicleBO.setDriverId(list);
        return vehicleBO;
    }


    /**
     * 牵引车完善信息状态
     *
     * @param carrierId
     * @param typeCode
     * @param subjectCode
     * @return
     */
    @Override
    public Boolean getCarrierStatus(Long carrierId, String typeCode, String subjectCode) {
        Boolean blnCarrierStatus = true;
        //判断证照信息
        LicenseTypeVo licenseTypeBO = mdmUtil.getLicenseTypeByCode(typeCode, subjectCode);
        if (Objects.isNull(licenseTypeBO)) {
            throw new BaseException("缺少证照类型");
        }
        EntityWrapper<CarrierLicense> ewdl = new EntityWrapper<>();
        ewdl.eq("license_type_id", licenseTypeBO.getId());
        ewdl.eq("carrier_id", carrierId);
        List<CarrierLicense> dls = carrierLicenseService.selectList(ewdl);
        if (!org.apache.commons.collections4.CollectionUtils.isEmpty(dls)) {
            CarrierLicense carrierLicense = dls.get(0);
            CarrierLicenseBO vehicleLicenseBO = new CarrierLicenseBO();
            BeanUtils.copyProperties(carrierLicense, vehicleLicenseBO);
            if (Objects.nonNull(vehicleLicenseBO.getId())) {
                EntityWrapper<CarrierLicenseAttach> ew = new EntityWrapper<>();
                ew.eq("carrier_id", carrierId).eq("license_id", vehicleLicenseBO.getId());
                List<CarrierLicenseAttach> carrierLicenseAttachs = carrierLicenseAttachService.selectList(ew);
                if (org.apache.commons.collections4.CollectionUtils.isEmpty(carrierLicenseAttachs)) {
                    blnCarrierStatus = false;
                }
            } else {
                blnCarrierStatus = false;
            }

        }
        return blnCarrierStatus;
    }

    @Override
    public Page<WeChatVehicle> queryPageVehicle(Page<WeChatVehicle> page, String authorization) {
        Wrapper<WeChatVehicle> ew = buildVehicleCondition(page.getCondition());
        List<WeChatVehicle> vehicleList = baseMapper.selectPageVehicle(page, ew);
        if (!CollectionUtils.isEmpty(vehicleList)) {
            for (WeChatVehicle weChatVehicle : vehicleList) {
                if (Objects.nonNull(weChatVehicle.getTrailerTypeId())) {
                    List<TransportationTypeVO> allServiceType = mdmUtil.getAllFleetTransportType();
                    String serviceTypeName = weChatVehicle.getTrailerTypeId();
                    for (TransportationTypeVO transportationTypeVO :
                            allServiceType) {
                        serviceTypeName = serviceTypeName.replaceAll(transportationTypeVO.getCode(), transportationTypeVO.getValue());
                    }
                    weChatVehicle.setTrailerTypeName(serviceTypeName);
                }
                if (Objects.nonNull(weChatVehicle.getTractorType())) {
                    if (TractorTypeEnum.TRACTORVEHICLE.getCode().toString().equals(weChatVehicle.getTractorType()))
                        weChatVehicle.setTractorTypeName(TractorTypeEnum.TRACTORVEHICLE.getText());
                    if (TractorTypeEnum.RECOVERYVEHICLE.getCode().toString().equals(weChatVehicle.getTractorType()))
                        weChatVehicle.setTractorTypeName(TractorTypeEnum.RECOVERYVEHICLE.getText());
                }
            }
        }
        page.setRecords(vehicleList);
        return page;
    }

    @Override
    public List<CarrierInfo> selectCarrierListNoTenant(Wrapper<CarrierInfo> ew) {
        return this.baseMapper.selectCarrierNoTenant(ew);
    }

    @Override
    public WeChatVehicle getWeChatVehicleById(Long id) {
        return baseMapper.selectVehicleById(id);
    }

    @Override
    public Boolean verifyCarrier(Long list, String plate) {
        CarrierTrailerVO carrierTrailerVO = new CarrierTrailerVO();
        //判断司机的认证状态
        Driver driver = driverService.selectById(list);
        if (Objects.isNull(driver)) {
            throw new BaseException("司机信息不存在");
        }
//
        //司机在“未认证”状态下，绑定的牵引车，不能为已在库的
        // TODO 微信端解除司机未认证可以绑定车辆
        /*if (driver.getAuthStatus().equals(AuthStatusEnum.UNAUTHORIZED.getCode())) {
            //根据车牌号得到牵引车信息
            EntityWrapper<CarrierInfo> carrierInfoEntityWrapper = new EntityWrapper<>();
            carrierInfoEntityWrapper.eq("plate", plate);
//            List<CarrierInfo> carrierInfoList = this.selectList(carrierInfoEntityWrapper);
            List<CarrierInfo> carrierInfoList = selectCarrierListNoTenant(carrierInfoEntityWrapper);
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(carrierInfoList)) {
                throw new BaseException("您未认证，无法在进行绑定已经在库的牵引车！");
            }
        }*/
//
//        //司机在“已认证”状态下，可以选择已在库并且“已认证”的牵引车，若该牵引车当前已绑定挂车，则自动带出挂车信息，司机不得修改挂车信息；若该牵引车当前未绑定挂车，司机可录入新挂车，也可选择在库且未绑定牵引车的挂车。
        if (driver.getAuthStatus().equals(AuthStatusEnum.CERTIFICATION.getCode())) {
//            //根据车牌号得到牵引车信息
            EntityWrapper<CarrierInfo> carrierInfoEntityWrapper = new EntityWrapper<>();
            carrierInfoEntityWrapper.eq("plate", plate);
            List<CarrierInfo> carrierInfoList = selectCarrierListNoTenant(carrierInfoEntityWrapper);
//            //如果是已经在库的牵引车
            if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(carrierInfoList)) {
//                //判断的逻辑：不能绑定其他承运商的车；不能绑定已绑定其他司机的车；当前已认证的司机不能绑定未认证的车
                CarrierInfo carrierInfo = carrierInfoList.get(0);
//                    //不能绑定未认证的车
//                if (carrierInfo.getAuthStatus().equals(AuthStatusEnum.UNAUTHORIZED.getCode())) {
//                    throw new BaseException("该牵引车没有进行认证，无法进行绑定");
//                }
//                //不能绑定其他承运商的车；
                Long lspId = driver.getLspId();
                if (!carrierInfo.getLspId().equals(lspId)) {
                    throw new BaseException("该牵引车属于其他承运商，无法进行绑定！");
                }
                //不能绑定已绑定其他司机的车；
                Long carrierId = carrierInfo.getId();
                DriverCarrierBind driverCarrierBind = driverCarrierBindService.getCarrierBindByCarrierIdNoDriId(carrierId, list);
                if (Objects.nonNull(driverCarrierBind)) {
                    throw new BaseException("该牵引车已经绑定其他司机，无法进行绑定！");
                }
            }
        }


        return true;
    }


    /**
     * 添加车与司机的绑定
     *
     * @param carrierPlate
     * @param driver
     * @return
     */
    private CarrierInfo addCarrierBindByDriver(String carrierPlate, Driver driver) {
        CarrierInfo carrierInfo;
        Object user = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

        if (Objects.isNull(driver)) {
            throw new BaseException("司机信息不存在");
        }

        //先判断是否牵引车是否在库
        EntityWrapper<CarrierInfo> carrierInfoEntityWrapper = new EntityWrapper<>();
        carrierInfoEntityWrapper.eq("plate", carrierPlate);
        List<CarrierInfo> carrierInfoList = baseMapper.selectCarrierNoTenant(carrierInfoEntityWrapper);
        if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(carrierInfoList)) {
            carrierInfo = carrierInfoList.get(0);
        } else {
            //不在库则新建
            carrierInfo = new CarrierInfo();
            carrierInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
            carrierInfo.setLspId(driver.getLspId());
            carrierInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
            carrierInfo.setCreateFrom(SourceEnum.WEIXIN.getText());
            carrierInfo.setPlate(carrierPlate);
            carrierInfo.setCreator(user.toString());
            carrierInfo.setTenantId(driver.getTenantId());
            this.insert(carrierInfo);
        }

        //判断牵引车和司机是否已经是是绑定关系，如果不是，则进行校验
        DriverCarrierBind driverCarrierBind = driverCarrierBindService.getCarrierBindByCarIdAndDriId(carrierInfo.getId(), driver.getId());
        if (Objects.isNull(driverCarrierBind)) {
            //新建绑定关系
            driverCarrierBind = new DriverCarrierBind();
            driverCarrierBind.setCarrierId(carrierInfo.getId());
            driverCarrierBind.setDriverId(driver.getId());
            driverCarrierBind.setGmtCreate(new Date());
            driverCarrierBindService.insert(driverCarrierBind);
            //编写绑定关系的日志
            DriverCarrierBindLog log = new DriverCarrierBindLog();
            log.setCarrierId(carrierInfo.getId());
            log.setDriverId(driver.getId());
            log.setGmtCreate(new Date());
            driverCarrierBindLogService.insert(log);
        }

        return carrierInfo;
    }


    @Override
    public CarrierInfoBO selectByDriverId(Long driverId) {
        return baseMapper.selectByDriverId(driverId);
    }

    private Wrapper<WeChatVehicle> buildVehicleCondition(Map<String, Object> condition) {
        Wrapper<WeChatVehicle> ew = new EntityWrapper<>();

        if (!StringUtils.isEmpty(condition.get("plate"))) {
            ew.like("plate", condition.get("plate").toString());
        }

        if (!StringUtils.isEmpty(condition.get("trailerPlate"))) {
            ew.like("trailer_plate", condition.get("trailerPlate").toString());
        }

        ew.orderBy("gmt_create", false);
        return ew;
    }

    /**
     * 更新牵引车信息不存在创建
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CarrierInfo updateCarrier(CarrierInfo carrierInfo) {
        try {
            if (Objects.isNull(carrierInfo)) {
                throw new BaseException("请写入牵引车信息");
            }
            if (StringUtils.isEmpty(carrierInfo.getPlate())) {
                throw new BaseException("车牌号不能为空");
            }
            if (carrierInfo.getPlate().contains("挂")) {
                throw new BaseException("车牌号有误:含挂字");
            }
            // 校验数据
            CarrierInfo nameExistCarrier = getPlanExistCarrier(carrierInfo);
            if (Objects.nonNull(nameExistCarrier)) {
                throw new BaseException(CarrierEnum.PLATE_EXIST.getCode(), "该车牌号已被使用");
            }
            if (Objects.isNull(carrierInfo.getLspId())) {
                throw new BaseException("未选择承运商");
            }
            LspInfo lspInfo = lspInfoService.selectById(carrierInfo.getLspId());
            if (Objects.nonNull(lspInfo.getId())) {
                carrierInfo.setLspId(lspInfo.getId());
                carrierInfo.setTenantId(lspInfo.getTenantId());
            }
            if (Objects.isNull(carrierInfo.getId())) {
                JwtAccountVO jwtAccount = AccountUtil.getAccountInfoFromSecurityContext();
                //绑定验证信息
                carrierInfo.setStatus(StatusEnum.DISCONTINUAT.getCode());
                carrierInfo.setAuthStatus(AuthStatusEnum.UNAUTHORIZED.getCode());
                carrierInfo.setCreateFrom(SourceEnum.LSPM.getText());
                carrierInfo.setGmtCreate(new Date());
                if (Objects.nonNull(jwtAccount)) {
                    carrierInfo.setCreator(jwtAccount.getAccountId());
                }
                this.insert(carrierInfo);
            } else {
                carrierInfo.setGmtUpdate(new Date());
                this.updateById(carrierInfo);
            }
            return carrierInfo;
        } catch (BaseException e) {
            LOGGER.error("CarrierInfoServiceImpl.updateCarrier" + e.getMessage());
            throw e;
        } catch (Exception e) {
            LOGGER.error("CarrierInfoServiceImpl.updateCarrier" + e.getMessage());
            throw new BaseException("保存牵引车信息失败");
        }
    }

    /**
     * 获取承运商单条信息
     *
     * @param carrierId
     * @return
     */
    @Override
    public CarrierBasicVO getCarrierInfoLine(Long carrierId) {
        CarrierBasicVO carrierInfoLineVO = new CarrierBasicVO();
        if (Objects.isNull(carrierId)) throw new BaseException("请传入牵引车信息");
        EntityWrapper<CarrierInfo> ew = new EntityWrapper<>();
        ew.eq("id", carrierId);
        List<CarrierInfo> carrierInfos = baseMapper.selectCarrierNoTenant(ew);
        CarrierInfo carrierInfo = carrierInfos.get(0);
        if (Objects.isNull(carrierInfo)) throw new BaseException("未找到对应牵引车信息");

        // 拿车队ID查询车队名
        if (Objects.nonNull(carrierInfo.getFleetId())) {
            Fleet fleet = fleetService.selectByIdNoTenant(carrierInfo.getFleetId());
            if (Objects.nonNull(fleet)) {
                carrierInfoLineVO.setFleetName(fleet.getFleetName());
            }
        }

        BeanUtils.copyProperties(carrierInfo, carrierInfoLineVO);
        if (Objects.nonNull(carrierInfo.getLspId())) {
            LspInfo lspInfo = lspInfoService.selectById(carrierInfo.getLspId());
            if (lspInfo != null) {
                carrierInfoLineVO.setLspName(lspInfo.getName());
            }
        }
        // 查询挂车
        EntityWrapper<CarrierTrailerBind> ewT = new EntityWrapper<>();
        ewT.eq("carrier_id", carrierId);
        List<CarrierTrailerBind> carrierTrailerBinds = carrierTrailerBindService.selectList(ewT);
        if (null != carrierTrailerBinds && !carrierTrailerBinds.isEmpty()) {
            carrierInfoLineVO.setTrailerId(carrierTrailerBinds.get(0).getTrailerId());
        }
        return carrierInfoLineVO;
    }

    /**
     * 根据车牌号匹配获取牵引车
     */
    private CarrierInfo getPlanExistCarrier(CarrierInfo carrierInfo) {
        Wrapper<CarrierInfo> plateCarrierEntity = new EntityWrapper<>();
        plateCarrierEntity.eq("plate", carrierInfo.getPlate().trim())
                .ne("is_delete", TableStatusEnum.STATUS_1.getCode());
        if (Objects.nonNull(carrierInfo.getId())) {
            plateCarrierEntity.ne("id", carrierInfo.getId());
        }
        List<CarrierInfo> plateCarrierList = baseMapper.selectCarrierNoTenant(plateCarrierEntity);
        if (!CollectionUtils.isEmpty(plateCarrierList)) {
            return plateCarrierList.get(0);
        }
        return null;
    }

    @Override
    public Integer updateLsp(CarrierInfo carrierInfo) {
        return baseMapper.updateLsp(carrierInfo);
    }

    /**
     * 根据id号，恢复指定牵引车的删除状态
     *
     * @param ids
     * @return
     */
    @Override
    public List<String> updateDeleteStatus(List<Long> ids) {
        try {
            List<String> msgs = new ArrayList<>();
            if (CollectionUtils.isEmpty(ids)) throw new BaseException("请选择恢复删除的牵引车");
            for (Long id : ids) {
                String msg = "";
                EntityWrapper<CarrierInfo> carrierInfoEntityWrapper = new EntityWrapper<>();
                carrierInfoEntityWrapper.eq("id", id);
                List<CarrierInfo> carrierInfos = baseMapper.selectCarrierNoTenant(carrierInfoEntityWrapper);
                CarrierInfo carrierInfo = carrierInfos.get(0);
                if (Objects.isNull(carrierInfo)) {
                    msg = "牵引车:" + carrierInfo.getPlate() + ":牵引车不存在";
                    msgs.add(msg);
                    continue;
                }
                baseMapper.updateDeleteStatus(carrierInfoEntityWrapper);
            }
            return msgs;
        } catch (BaseException e) {
            throw e;
        } catch (Exception e) {
            throw new BaseException("恢复失败");
        }
    }

    @Override
    public WeChatVehicle selectVehicleByCarrierIdOrTrailerId(Long id, Long trailerId) {
        return baseMapper.selectVehicleByCarrierIdOrTrailerId(id, trailerId);
    }

    @Override
    public void vehicleToOtm(Long id, String authorization) {
        Wrapper<CarrierInfo> wrapper = new EntityWrapper<>();
        wrapper.eq("lsp_id", id);
        List<CarrierInfo> carrierInfos = this.selectList(wrapper);
        for (CarrierInfo carrierInfo : carrierInfos) {
            carrierAndTrailerToOtm(carrierInfo.getId(), IntegrationEnum.ISACTIVE.getCode());
        }
    }

    @Override
    public WeChatVehicle selectVehicleByCTNoTenant(Long id, Long tid) {
        return baseMapper.selectVehicleByCTNoTenant(id, tid);
    }

    @Override
    public CarrierInfoBO selectByDriverIdNoTenant(Long driverId) {
        return baseMapper.selectByDriverIdNoTenant(driverId);
    }
}
